构造函数中的方法与函数原型属性之间的区别

时间:2012-05-24 10:41:12

标签: javascript prototype-programming

  

可能重复:
  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);
    }
}

并修改了一个利用原型属性:

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”。

那么有人可以向我解释一下这个差异以及为什么选择一个而不是另一个?

1 个答案:

答案 0 :(得分:3)

以下是a post I recently didhere's a demo。在演示中,请查看Test2以及foobar位于链中的位置。

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附加的那些出现在该对象的所有实例上并且是“共享的”。修改该属性会更改所有实例的此属性。

相关问题