Reputation: 521
Is is necessary to have "prototype" appended to every method of class.. or namespace is enough in example below (for full example refer link below). I understand that it is good practice but do inheritance really require the keyword "prototype" declare in every method.. what is the real necessity inheritance
if(animal === undefined) var animal = {};
animal.Mammal.prototype.haveABaby=function(){
var newBaby=new Mammal("Baby "+this.name);
this.offspring.push(newBaby);
return newBaby;
}
animal.Mammal.prototype.toString=function(){
return '[Mammal "'+this.name+'"]';
}
http://phrogz.net/JS/classes/OOPinJS2.html
Upvotes: 1
Views: 82
Reputation: 382132
prototype has nothing to see with namespace.
You define a function on prototype so that all objects created with new Mammal()
will have this function (method) :
Mammal.prototype.haveABaby=function(){
...
var phoque = new Mammal();
var d = phoque.haveABaby();
In this case, all instances will share the same function. If you'd had defined the function on your instance, you'd have used more memory (not necessarily significant), and instance creation would have been longer.
If you want, you may combine it with namespaces :
animal = animal || {}; // note the simplification
animal.Mammal.prototype.haveABaby=function(){
...
var phoque = new animal.Mammal();
var d = phoque.haveABaby();
But those are two different topics.
Here's a good description of the link between prototype and inheritance.
Upvotes: 2
Reputation: 1014
it's needed.
If you don't have prototype then the function only gets added to the current instance. Using prototype means that when you user the new keyword, the new object will also get a copy of the function.
ie:
Mammal.toString = function() {...};
would put the toString function on Mammal - but would NOT put a toString function on every instance of Mammal. e.g. using the above non-prototype declaration:
var aDog = new Mammal();
aDog.toString() //result in undefined
Upvotes: 1