Can anybody help me understand why the "counter" property seems to get reset on every new instance? I expected it to work like the "letters" property, which is shared across all instantiated objects.
I came across this while putting together some sample code as to why prototype properties shouldn't be used this way unless they are intended to be static.
Sample Code:
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 += amountis actually doingthis.counter = Dog.Prototype.counter + 1