Possible Duplicate:
Use of 'prototype' vs. 'this' in Javascript?
I am confused with these two type of adding a method to a function. Let me explain with an example.
var foo = function(){ this.bar = function(){alert('I am a method')} } foo.prototype.baz = function(){alert('I am another method')} var car = new foo();
Now at this point we can use baz and bar methods for car. Well, but what is the difference between them. What is the nuance adding a method to function's prototype or it's constructor.
Thanks..
This gives each foo instance a bar method of its own. So,
In the second case:
You are attaching a function to the prototype chain of the function foo. So, each instance gets the same method.
Changing baz would change the function on each instance as each instance inherits the same function.The advantage of the second approach is clear in terms of inheritance. Also, in the first approach, since you are attaching a method to each specific instance, it won't scale if you are creating several foo instances as each instance would unnecessarily have a copy of the same method.
Functions assigned to the
prototype
will be shared by all instances; functions assigned in the constructor will have a separate function object per instance.Also, functions assign in the constructor can use the constructor's variables and parameters.
For example: