有必要将“原型(prototype)”附加到类的每个方法......或命名空间在下面的示例中就足够了(完整示例请引用下面的链接)。我知道这是一种很好的做法,但是继承确实需要在每个方法中声明关键字“原型(prototype)”。什么是真正必要的继承
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+'"]';
}
最佳答案
原型(prototype)与命名空间无关。
您在原型(prototype)上定义一个函数,以便所有使用 new Mammal()
创建的对象都将具有此函数(方法):
Mammal.prototype.haveABaby=function(){
...
var phoque = new Mammal();
var d = phoque.haveABaby();
在这种情况下,所有实例将共享相同的功能。如果您已经在您的实例上定义了该函数,您会使用更多内存(不一定重要),并且实例创建时间会更长。
如果你愿意,你可以将它与命名空间结合起来:
animal = animal || {}; // note the simplification
animal.Mammal.prototype.haveABaby=function(){
...
var phoque = new animal.Mammal();
var d = phoque.haveABaby();
但这是两个不同的主题。
Here's a good description of the link between prototype and inheritance.
关于javascript - 每个方法中原型(prototype)声明的必要性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12678572/