javascript - 每个方法中原型(prototype)声明的必要性

标签 javascript

有必要将“原型(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+'"]';
} 

http://phrogz.net/JS/classes/OOPinJS2.html

最佳答案

原型(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/

相关文章:

javascript - HTML 输入元素范围检测拖动何时结束

javascript - 如何在 SoundCloud 上通过 Javascript SDK 获取 access_token?

javascript - 单击按钮时通过 javascript 调用 JSP 页面

javascript - 如何通过它的 id 删除我的 ul 中的所有 li?

JavaScript 匹配

javascript - 哪种方式更好,setInterval() 或 window.setInterval()?

javascript - javascript 中的 json 值到字符串数组

javascript - div 内的曲线 Angular 图像问题

javascript - 不使用数组检测具有最大值的变量?

javascript - 有没有办法在有序列表中设置列表类型的样式?