2016-07-16 82 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 

避免改变构造函数中的原型总是比较好的。因为这样做会造成不必要的混乱。