【发布时间】:2013-09-26 06:55:32
【问题描述】:
谁能帮我理解为什么“计数器”属性似乎在每个新实例上都会重置?我希望它能够像“字母”属性一样工作,该属性在所有实例化对象之间共享。
我在整理一些示例代码时遇到了这个问题,说明为什么原型属性不应该以这种方式使用,除非它们是静态的。
示例代码:
var Dog = function() {
this.initialize.apply(this, arguments);
};
Dog.prototype = {
counter : 2,
letters : [ 'a', 'b', 'c' ],
initialize : function(dogName) {
this.dogName = dogName;
},
add : function(amount) {
this.counter += amount;
},
arr : function(char) {
this.letters.push(char);
}
};
var fido = new Dog("fido");
fido.add(1);
fido.arr('d');
console.log(fido.counter); // 3, as expected
console.log(fido.letters.toString()); // ABCD, as expected
var maxx = new Dog("maxx");
maxx.add(1);
maxx.arr('e');
console.log(maxx.counter); // 3, Unexpected, Why isn't this 4?
console.log(maxx.letters.toString()); // ABCDE, as expected
【问题讨论】:
-
因为你的线路
this.counter += amount实际上是在做this.counter = Dog.Prototype.counter + 1
标签: javascript prototype instance-variables javascript-objects