2012-01-26 67 views
1

我試圖做繼承,但我沒想到this.array會像靜態成員一樣行事。我怎樣才能使 '保護/公衆':JavaScript:繼承

function A() { 
    this.array = []; 
} 

function B() { 
    this.array.push(1); 
} 
B.prototype.constructor=B; 
B.prototype = new A(); 

螢火蟲:

>>> b = new B(); 
A { array=[1]} 
>>> b = new B(); 
A { array=[2]} 
>>> b = new B() 
A { array=[3]} 
+0

順便說一句,你最後兩行是倒退的。 *設置'prototype'之後設置'prototype.constructor' *。 – Ryan

+0

我意識到這只是一個例子,但爲什麼不''this.array = [1]'呢? – Ryan

+0

原始代碼如下所示: function Controller(uri){this._controllerURI = uri; this._controllers = []; this._views = []; this._events = []; }。這只是一個例子。 – DraganS

回答

3

不是 「私有/保護」,但是這樣會讓每個B一個新的陣列。

function A() { 
    this.array = []; 
} 

function B() { 
    A.apply(this); // apply the A constructor to the new object 
    this.array.push(1); 
} 
// B.prototype.constructor=B; // pointless 
B.prototype = new A(); 
+0

我想你是指'A.call(this);'。 – Ryan

+0

@user(\ d)*完美。謝謝。 @minitech:可以申請 - 它的作品。在哪裏可以找到您的$ Query替換文檔/示例代碼? – DraganS