Gustavo Muñoz - justavo, kanchenjungo, zipi

June 3, 2005

Prototype and instance properties in JavaScript

Filed under: Technology

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);
    }
};






















Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham