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?