谁能帮我理解为什么“计数器”属性似乎在每个新实例上都会重置?我希望它像“字母”属性一样工作,该属性在所有实例化对象中共享。
我在整理一些示例代码时遇到了这个问题,为什么不应该以这种方式使用原型属性,除非它们是静态的。
示例代码:
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