2013-04-04 81 views
1

正在学习原型。将函数“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(); 
+0

可能重复(http://stackoverflow.com/questions/15497259/ JavaScript中的重写方法) – 2013-04-04 08:26:39

回答

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的所有调用。

1

这是更好地使用原型共享资源

+0

如果您在原型中使用普通对象,则会产生一个缺陷 - 它们可能会出乎意料地从一个实例变为另一个实例。 – David 2013-04-04 08:33:58