Possible Duplicate:
Advantages of using prototype, vs defining methods straight in the constructor?
我试图掌握 JavaScript 中的原型(prototype)属性,但遇到了麻烦。
我遵循了一个教程,其中指出:
“因此所有对象都会自动共享 sayHello() 方法/函数,我们必须将其分配给 protoype 属性”。
现在提到的原始代码是:
function Pet(name, species, hello)
{
this.name = name;
this.species = species;
this.hello = hello;
this.sayHello = function()
{
alert(this.hello);
}
}
以及利用原型(prototype)属性的修改:
function Pet(name, species, hello)
{
this.name = name;
this.species = species;
this.hello = hello;
}
Pet.prototype.sayHello = function()
{
alert(this.hello);
}
这里有什么区别,因为这两种方法都会产生相同的结果(据我所知)。例如,以下代码与上述任一代码组合时的行为相同:
var rufus = new Pet("Rufus", "cat", "miaow");
rufus.sayHello();
在这两种情况下,都会发出“miaow”警报。
有人可以向我解释一下其中的区别以及为什么您会选择其中一个而不是另一个吗?
最佳答案
这是a post I recently did关于这一点和here's a demo 。在演示中,查看 Test2
以及 foo
和 bar
在链中的位置。
var Test2 = function() { //foo attached via constructor
this.foo = 'foo'; // each instance has "it's own" foo
}
Test2.prototype.bar = function() {}; //bar attached via prototype
// all instances "share" the same bar
var mytest2 = new Test2();
(3) <-------- (2) <--------- (1) <- prototype chain
Object -> Test2 prototype -> mytest2
'--> bar '--> bar (from prototype)
'--> foo (from constructor)
基本上,通过构造函数附加的任何内容都会出现在每个实例中,但“属于该实例”。从实例修改该属性只会在当前实例中修改它。
另一方面,通过原型(prototype)
附加的那些出现在该对象的所有实例上并且是“共享的”。修改该属性会更改所有实例的该属性。
关于javascript - 构造函数中的方法与函数原型(prototype)属性之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10735876/