What is the difference between function assignment via "this" vs. "prototype"?

Possible duplicate:
Using a “prototype” versus “this” in Javascript?

I am confused with these two types 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 stage we can use the baz and bar methods for the car. Well, but what is the difference between the two. What is a nuance that adds a method to work with a prototype or constructor.

Thank..

+5
2

, prototype, ; , , .

, , , .

:

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

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

var car = new foo("Hi there!");
car.bar();
+9
var foo = function(){
    this.bar = function(){alert('I am a method')}
}

foo . ,

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

:

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

foo. , . baz , .

. , , , , foo, .

+1

All Articles