2

我目前正在学习原型。将函数“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();
4

3 回答 3

2

不一样,因为第一个版本将使用更多内存,因为实例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

因为dog并且alligator不共享相同的函数sayName,而在后一个示例中对原型的更改将更改对sayName.

于 2013-04-04T08:19:28.933 回答
1

共享资源最好使用原型

于 2013-04-04T08:20:01.143 回答
1

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

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

您还应该阅读以下文章:

  1. http://javascript.crockford.com/private.html
  2. https://stackoverflow.com/a/8096017/783743
于 2013-04-04T08:23:54.360 回答