Possible Duplicate:
Use of 'prototype' vs. 'this' in Javascript?
I went to various websites but not able to understand the difference between the following ways of adding methods to custom objects:
Method 1:
function circle(radius){
this.radius = radius;
this.area = function(){ return 3.14*this.radius*this.radius;}
}
Method 2:
function circle(radius){
this.radius = radius;
}
circle.prototype.area = function(){ return 3.14*this.radius*this.radius; }
Are there any performance or design issues that one of the methods has and the other does not?
Here is one way to see the difference:
For Method1 you will see
falsewhile Method2 yields intrue. That’s because in the first case you assign a new closure function to each object created, two objects end up with differentareafunctions even though both do the same thing. In the second case the objects share the same prototype object with itsareamethod, that method is of course identical in both cases.Usually Method2 is preferable for several reasons:
Object.hasOwnProperty.There are some disadvantages as well to keep in mind.
Here is an example of the common mistake:
The correct approach here would be: