javascript - 当我只能将 "attach"函数传递给构造函数时,为什么要使用原型(prototype)?

标签 javascript

Possible Duplicate:
Use of ‘prototype’ vs. ‘this’ in Javascript?
Advantages of using prototype, vs defining methods straight in the constructor?

我正在学习 Javascript 中的原型(prototype)。我不太明白的一件事是为什么我应该使用 CONSTRUCTOR_FN.prototype.METHOD_NAME 添加函数约定而不仅仅是使用 this.METHOD_NAMECONSTRUCTOR 的正文中?

我写了这段小代码来澄清:

function Cat ( name ) {
    this._name = name;
    this.say = function ( thing ) {
        alert( this._name + " says: '" + thing + "'" );
    }
}

function Dog ( name ) {
    this._name = name;
}
Dog.prototype.say = function ( thing ) {
    alert( this._name + " says: '" + thing + "'" );
}

var c = new Cat( "Mitt");
var d = new Dog( "Barak" );
c.say( "War" );
d.say( "No war" );

据我所知,CatDog构造函数的工作原理相同。如果我从this question理解正确的是,唯一的区别是,当您向原型(prototype)添加某些内容时,该构造函数中的所有对象都将拥有它。还有其他原因吗?

最佳答案

事实上,是有区别的。当您通过原型(prototype)添加方法或属性时,您可以确保该方法/属性只会创建一次,并且它们将包含在原型(prototype)对象中。但是,如果您只是将方法添加到函数中,则该方法将随类的每个新实例一起克隆。假设您的类中有 10 个对象实例。如果您使用原型(prototype),那么这 10 个实例将只有 1 个方法。如果您向函数对象本身添加方法,您将拥有 10 个方法副本。

关于javascript - 当我只能将 "attach"函数传递给构造函数时,为什么要使用原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12859452/

相关文章:

javascript - 将 anchor 与 react 路由器一起使用

javascript - 使用 jQuery 添加类后的转换未按预期工作

javascript - 调用前验证JS方法是否存在

javascript - 如何从 Xpath 中隔离可在 document.querySelector 中使用的选择器?

javascript - 为什么添加到一个 IFRAME 的 String.prototype 的属性在使用 IFRAME 的 String 函数创建的字符串对象中不可用?

javascript - nsITraceableChannel,拦截HTTP流量代码

javascript - DatePicker 默认为今天

javascript - Google AppMaker 'SearchText' 参数值的预期日期?

javascript - Node.js/Express.js/Angular2 中的 ForBiddenError

javascript - 将 Vue.js 集成到现有 ASP.NET MVC5 项目的最佳方式