可能重複:
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();
在這兩種情況下,這提示「咪」。
所以可能有人請向我解釋的差異,你爲什麼會選擇一個比其他?
的可能重複的[使用原型,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對象方法] -原型)。 –
我覺得這是最未搜索問題的一個:) – fcalderan
另外這一個:http://stackoverflow.com/questions/892595/javascript-prototypal-inheritance –