Could someone shed light on why the "counter" property appears to reset with every new instance? I was anticipating it to function similarly to the "letters" property, which is shared among all instantiated objects.
I stumbled upon this issue while testing some code snippets to demonstrate why prototype properties should not be used in this manner unless they are meant to be static.
Test Code:
var Cat = function() {
this.initialize.apply(this, arguments);
};
Cat.prototype = {
counter : 2,
letters : [ 'a', 'b', 'c' ],
initialize : function(catName) {
this.catName = catName;
},
add : function(amount) {
this.counter += amount;
},
arr : function(char) {
this.letters.push(char);
}
};
var whiskers = new Cat("whiskers");
whiskers.add(1);
whiskers.arr('d');
console.log(whiskers.counter); // 3, as expected
console.log(whiskers.letters.toString()); // ABCD, as expected
var mittens = new Cat("mittens");
mittens.add(1);
mittens.arr('e');
console.log(mittens.counter); // 3, Unexpected. Why isn't this 4?
console.log(mittens.letters.toString()); // ABCDE, as expected