2016-07-16 80 views
2

私有變量考慮下面的代碼:JavaScript和構造原型

var Test = function() { 
    var self = this; 
    var innerPrivate = 1; 
    self.innerPublic = 1; 
    self.innerShow = function() { 
    console.log(innerPrivate++ + ':' + this.innerPublic++); 
    }; 
    this.constructor.prototype.protoShow = function() { 
    console.log(innerPrivate++ + ':' + this.innerPublic++); 
    }; 
}; 

var t1 = new Test(); 
var t2 = new Test(); 

t2.innerShow(); //1:1 
t1.innerShow(); //1:1 
t2.innerShow(); //2:2 
t1.innerShow(); //2:2 

t2.protoShow(); //3:3 (expected: 1:3 or 3:3) 
t1.protoShow(); //4:3 (expected: 2:3 or 3:3) 
t2.protoShow(); //5:4 (expected: 3:4 or 4:4) 
t1.protoShow(); //6:4 (expected: 4:4) 

爲什麼內部變量都重新使用和共享?

即使實例鏈接到構造函數,結果仍然看起來不正確。

我錯過了什麼?

回答

1

基本上原型是類(函數)的實時連接。無論何時從類中創建新實例,這些實例都將共享原型屬性。變量innerPrivate是內部函數的閉包,但它將使用最後一個實例的變量進行更新。

. 
. 
var t1 = new Test(); 
var t2 = new Test(); 
// after execution of the above line 
//closure innerPrivate inside of prototype function is replaced with t2's innerPrivate. 

//So updating t1's innerPrivate via innerShow of it(t1) 
//doesn't affect the closure inside of protoShow 

避免改變構造函數中的原型總是比較好的。因爲這樣做會造成不必要的混亂。