Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should you use "prototype" during object augmentation in javascript?

I'm confused about the notion of "prototype" in javascript.

When I'm defining an object both of the following seem to work:

myObject = {};
myObject.prototype.method1 = function() { ... };
myObject.prototype.method2 = function() { ... };
myObject.prototype.method3 = function() { ... };

and...

myObject = {};
myObject.method1 = function() { ... };
myObject.method2 = function() { ... };
myObject.method3 = function() { ... };

Could anyone shed some light on this? What exactly is the difference between these two ways of creating an object and why would I choose one over the other? (I have this feeling in my gut it's important...)

Thanks!

like image 487
Travis Avatar asked Feb 16 '10 07:02

Travis


1 Answers

You should use the prototype property only on Constructor Functions, not in object instances, for example:

function Test () {}
Test.prototype.method1 = function () {/*...*/};

var obj = new Test();

The prototype property of constructor functions, is used by the new operator, when it creates our new object instance.

All native objects have a hidden link, that builds up the prototype chain.

This hidden link between objects is the [[Prototype]] internal property, and the new operator is the only one that can set it.

In the above example, the obj is associated internally with it's constructor prototype, the method1 is accessible from obj, but it doesn't exists physically on this object, that method exists on the Test.prototype object, and it's retrieved through the prototype chain, e.g.:

typeof obj.method1; // "function"
obj.hasOwnProperty('method1'); // false
obj.method1 === Test.prototype.method1; // true

On object instances, assigning a prototype property is meaningless, it will be taken just as any other property name:

var myObject = {};
myObject.prototype = "foo";
myObject.bar = "bar";

// myObject is simply {"prototype":"foo","bar":"bar"}
like image 176
Christian C. Salvadó Avatar answered Oct 04 '22 08:10

Christian C. Salvadó