Prototype and instance properties in JavaScript
I found a question about a strange behavior in JavaScript (apparently) on the AjaxBlog.
But the behavior that is posted there is the expected one because he is defining bar on a prototype basis and not on an instance one. It is different to define an instance property than a prototype property.
If you define Foo as the following:
function Foo(){
this.bar=[];
};
Foo.prototype= {
set: function(val) {
this.bar.push(val);
},
displayBar: function() {
alert(this.bar);
}
};
Not defining not bar inside the prototype, you will have a new, fresh array created for each instance.
This also creates an array for each instance:
var Class = {
newInstance: function() {
return function() {
this.c0nstructor.apply(this, arguments);
}
}
}
var MyFoo = Class.newInstance();
MyFoo.prototype= {
c0nstructor: function(){
this.bar=[];
},
set: function(val) {
this.bar.push(val);
},
displayBar: function() {
alert(this.bar);
}
};
But this doesn’t, for the same reason your code doesn’t do so:
MyFoo.prototype= {
bar=[],
c0nstructor: function(){
},
set: function(val) {
this.bar.push(val);
},
displayBar: function() {
alert (this.bar);
}
};

I guess put that way it makes perfect sense.
Was surprised when I first ran into it though - have never seen it demonstrated before - books like “JavaScript Definitive Guide” make no mention of this behaviour and turned up nothing while searching. Think it’s actually useful if you want something a bit like Java’s static keyword but needs cautious use.
Comment by Harry Fuecks — June 3, 2005 @ 2:42 am