Jamie Hutber
Jamie Hutber

Reputation: 28074

Why would I add a function to an objects prototype rather than add it to the object?

Somebody asked me this question and i was a little lost by it.

As this is a Q&A it makes sense to ask here.

Why would I add a function to an objects prototype rather than add it to the object?

Upvotes: 2

Views: 72

Answers (2)

punkrockbuddyholly
punkrockbuddyholly

Reputation: 9794

Consider these two objects:

Object 1

var myObject1 = function() {
    this.myProperty = true;
    this.myMethod = function() {
        return this.myProperty;
    };
}

Object 2

var myObject2 = function() {
   this.myProperty = true;
}

myObject2.prototype.myMethod = function() {
    return this.myProperty;
};

Everytime we do this:

var test = new myObject1();

myObject1.myMethod also gets created. Where as when we do this:

var test = new myObject2();

myObject2.myMethod does not have the overhead of needing to be created again because it was added to the prototype chain.

This wouldn't matter for a few instances but in a game, for example, where there could be hundreds of instances this can be quite a performance hit.


This net.tutsplus article may explain it better than me http://net.tutsplus.com/tutorials/javascript-ajax/prototypes-in-javascript-what-you-need-to-know/

Upvotes: 3

Justin Niessner
Justin Niessner

Reputation: 245419

Because, if you add it to the prototype it will be available on all "instances" of an object. If you add it to the object itself, it will only be available on that single instance.

Upvotes: 4

Related Questions