views:

74

answers:

2

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!

+6  A: 

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"}
CMS
Would add that many times there will be internally added methods to each instance inside the Constructor function via: this.fn = function(){...}; which is useful for having private instance variables that are accessed by instance methods.
Tracker1
+1  A: 

Second way adds methods only to this object. First way makes it available for other objects created with new with this "type".

zaharpopov