What is the difference between assigning a functio

2019-02-14 04:50发布

问题:

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

回答1:

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();


回答2:

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.