Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between assigning a function via "this" vs. "prototype"? [duplicate]

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..

like image 351
Fatih Acet Avatar asked Nov 24 '10 18:11

Fatih Acet


2 Answers

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:

var foo = function(param){
    this.bar = function() { alert('I can see a parameter: ' + param); };
}

foo.prototype.baz = function() { alert('I can't see foo's parameters'); };

var car = new foo("Hi there!");
car.bar();
like image 172
SLaks Avatar answered Sep 18 '22 05:09

SLaks


var foo = function(){
    this.bar = function(){alert('I am a method')}
}

This gives each foo instance a bar method of its own. So,

 var car1 = new foo();
 var car2 = new foo();
 car2.bar = //new function definition here.
 //car1.bar doesn't change.

In the second case:

foo.prototype.baz = function(){alert('I am another method')}

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.

like image 26
Rajat Avatar answered Sep 22 '22 05:09

Rajat