Possible Duplicate:
Advantages of using prototype, vs defining methods straight in the constructor?
I'm trying to get a grip on the prototype property in JavaScript but I'm having trouble.
I've followed a tutorial that states:
"So all objects automatically share the sayHello() method/function we must assign it to the protoype property".
Now the original code mentioned was:
function Pet(name, species, hello)
{
this.name = name;
this.species = species;
this.hello = hello;
this.sayHello = function()
{
alert(this.hello);
}
}
And the amended one to utilise the prototype property:
function Pet(name, species, hello)
{
this.name = name;
this.species = species;
this.hello = hello;
}
Pet.prototype.sayHello = function()
{
alert(this.hello);
}
What is the distinction here because both of these methods result in the same thing (from what I can tell). For instance the below code acts the same when grouped with either of the above:
var rufus = new Pet("Rufus", "cat", "miaow");
rufus.sayHello();
In both cases this alerts "miaow".
So could someone please explain to me the difference and why you would choose one over the other?
Here's a post I recently did about that and here's a demo. In the demo, take a look at Test2
and where foo
and bar
are located in the chain.
var Test2 = function() { //foo attached via constructor
this.foo = 'foo'; // each instance has "it's own" foo
}
Test2.prototype.bar = function() {}; //bar attached via prototype
// all instances "share" the same bar
var mytest2 = new Test2();
(3) <-------- (2) <--------- (1) <- prototype chain
Object -> Test2 prototype -> mytest2
'--> bar '--> bar (from prototype)
'--> foo (from constructor)
Basically, anything attached via constructor appears at every instance, but "belongs to that instance". Modifying that property from an instance only modifies it at the current instance.
On the other hand, the ones attached via the prototype
is appears on all instances of that object and are "shared". Modifying that property changes this property for all instances.