【问题标题】:whey append methods to the Object prototype instead of put them on constructor function ? [duplicate]乳清将方法附加到对象原型而不是将它们放在构造函数上? [复制]
【发布时间】:2013-03-22 21:20:40
【问题描述】:

这是我的问题,我有一个对象 Car 和他们的属性,我在对象内部定义了一个方法。但我认为建议将此方法附加到对象原型中,但为什么呢?有什么优点和缺点?谢谢你:)

我做了什么..

function Car (desc) {
    this.desc = desc;
    this.color = "red";
    this.getInfo = function getInfo() {
        return 'A ' + this.color + ' ' + this.desc + '.';
    };
}

推荐:

Car.prototype.getInfo = function() {
    return 'A ' + this.color + ' ' + this.desc + '.';
};

【问题讨论】:

标签: javascript jquery prototype


【解决方案1】:

您所做的会导致Car 的每个实例都拥有自己的getInfo 方法副本。将它放在原型上会自动为每个实例提供一个函数定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 2017-11-10
    • 1970-01-01
    • 2012-11-24
    • 2010-09-30
    • 1970-01-01
    • 2012-04-04
    相关资源
    最近更新 更多