【问题标题】:the prototype - add function to a class原型 - 将函数添加到类
【发布时间】:2013-04-04 08:17:39
【问题描述】:

我目前正在学习原型。将函数“sayName”放在类中还是稍后通过原型添加更好?还是一样,视情况而定?

function Animal(name,numLegs){
    this.name = name;
    this.numLegs = numLegs;
    this.sayName = function(){
         console.log("Hi my name is " + this.name);

    };
}


var penguin = new Animal("Captain Cook", 2);
penguin.sayName();

function Animal(name,numLegs){
    this.name = name;
    this.numLegs = numLegs;
}

Animal.prototype.sayName = function(){
    console.log("Hi my name is " + this.name);
};


var penguin = new Animal("Captain Cook", 2);
penguin.sayName();

【问题讨论】:

标签: javascript


【解决方案1】:

不一样,因为第一个版本将使用更多内存,因为Animal 的实例有自己的this.sayName。在后者中,所有Animal 实例都可以访问相同的 sayName

function Animal(name,numLegs){
    this.name = name;
    this.numLegs = numLegs;
    this.sayName = function(){
         console.log("Hi my name is " + this.name);
    };
}

var dog = new Animal(4, "Jack");
var alligator = new Animal(4, "Snap");

dog.sayName = function(){ console.log("woof"); }

dog.sayName();
alligator.sayName();

会导致

woof
Hi my name is Snap

因为dogalligator 不共享相同的函数sayName,而在后一个示例中更改原型会更改sayName 的所有调用。

【讨论】:

    【解决方案2】:

    共享资源最好使用原型

    【讨论】:

    • 如果您在原型中使用普通对象,就会有一个陷阱——它们会令人惊讶地从一个实例变异到另一个实例。
    【解决方案3】:

    这个问题已经得到解答 - 这取决于具体情况。阅读此答案:https://stackoverflow.com/a/15497685/783743

    如果您的方法需要访问构造函数的私有变量,那么您别无选择,只能在构造函数中定义它。否则,您应该始终在 prototype 对象上声明它们。

    您还应该阅读以下文章:

    1. http://javascript.crockford.com/private.html
    2. https://stackoverflow.com/a/8096017/783743

    【讨论】:

      猜你喜欢
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多