每种方法中原型声明的必要性



有必要将"原型"附加到类的每个方法中..或命名空间在下面的示例中就足够了(有关完整示例,请参阅下面的链接)。我知道这是很好的做法,但是继承确实需要在每个方法中声明关键字"原型"吗?什么是真正的必要性继承

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

原型与

命名空间无关。

您在原型上定义一个函数,以便使用 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();

但这是两个不同的话题。

下面很好地描述了原型和继承之间的联系。

这是

必需的。

如果您没有原型,则该函数仅添加到当前实例中。 使用 prototype 意味着当您使用 new 关键字时,新对象也将获得函数的副本。

即:

Mammal.toString = function() {...};

会将 toString 函数放在 Mammal 上 - 但不会在 Mammal 的每个实例上放置 toString 函数。 例如,使用上述非原型声明:

var aDog = new Mammal();
aDog.toString()  //result in undefined

最新更新