2012-05-24 59 views
0

可能重複:
Advantages of using prototype, vs defining methods straight in the constructor?差Vs函數的原型屬性

我試圖讓在JavaScript的原型屬性一握,但我遇到麻煩。

我跟着,指出一個教程:

「因此,所有的對象自動共享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(); 

在這兩種情況下,這提示「咪」。

所以可能有人請向我解釋的差異,你爲什麼會選擇一個比其他?

+1

的可能重複的[使用原型,VS在構造直定義方法的優點?](http://stackoverflow.com/questions/4508313/advantages-of-using-prototype-vs-defining-methods-straight-內式構造函數)和(http://stackoverflow.com/questions/9772307/declaring-javascript-object-method-in-constructor-function-vs-in [在原型構造函數與聲明javascript對象方法] -原型)。 –

+0

我覺得這是最未搜索問題的一個:) – fcalderan

+0

另外這一個:http://stackoverflow.com/questions/892595/javascript-prototypal-inheritance –

回答

3

這裏的a post I recently did關於那個和here'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附着的那些是出現在該對象的所有實例,並且「共享」。修改該屬性會爲所有實例更改此屬性。