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)
为什么内部变量都重新使用和共享?
即使实例链接到构造函数,结果仍然看起来不正确。
我错过了什么?