In creating javascript objects, I can put a method declaration either in the constructor function or in the prototype. For example, say I want a Dog class that has a Name property and a Bark method. I can put the declaration of the Bark method into the constructor function:
var Dog = function(name) {
this.Name = name;
this.Bark = function() {
alert(this.Name + " bark");
};
}
or I could put in as a method on the prototype object:
var Dog = function(name) {
this.Name = name;
}
Dog.prototype.Bark = function() {
alert(this.Name + " bark");
};
When I instantiate objects of type Dog, both approaches seem to work fine:
var dog = new Dog("Fido");
dog.Bark(); //Both approaches show "Fido bark"
Should I prefer one of these approaches over the other? Are there any advantages to using one over the other? Behind the scenes, do these two approaches end up doing exactly the same thing? Which approach do most people tend to favor?
Thanks for the help.