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

1 Comment »

The URI to TrackBack this entry is: http://justavo.blogsome.com/2005/06/03/49/trackback/

  1. 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

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>























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