2011-10-07 46 views
2
(function() { 
    window.gArr = new ExtArray(); 
})(); 

function ExtArray() { 
    this.bounce = function() { 
     document.write("Bounced successfully!"); 
    }; 
} 

ExtArray.prototype = new Array; 
ExtArray.prototype.first = function() { 
    document.write(this[0]); 
} 

var eArr = new ExtArray(); 
//all three work 
eArr.bounce(); 
eArr.push("I am first! "); 
eArr.first(); 
// invoking global 
gArr.bounce(); // it works 
gArr.push("No, it is me who is really first! "); // doesn't work 
gArr.first(); // doesn't work 

它爲什麼不起作用?爲什麼實例方法沒有按預期工作?

+0

什麼是觀察到的行爲?預期的行爲是什麼?他們有什麼不同? –

+0

gArr.push應該工作,gArr.first()應該輸出「不,它是我真正的第一個!」 – DrStrangeLove

+0

「請注意,構造函數的原型可以在任何時候改變,如果我們重新分配區域,那麼rect的新實例將在前幾個實例中具有不同的面積方法,更改原型不會影響創建對象的實例。「參考:http://xhalent.wordpress.com/2011/02/16/javascript-object-instantiation-and-prototypes/ –

回答

1
> (function() { 
>  window.gArr = new ExtArray(); })(); 

這是爲什麼優選只是:

var gArr = new ExtArray(); 

它們是功能上相同的(除非沒有窗口對象在這種情況下,首先會失敗);

> function ExtArray() { 
>  this.bounce = function() { 
>   document.write("Bounced successfully!"); 
>  }; } 

使用文件撰寫後的頁面加載完成後會首先清除整個文件(即HTML標籤之間的一切),寫無論是傳遞給函數(在這種情況下,兩字符串)。

> ExtArray.prototype = new Array; 
> ExtArray.prototype.first = function() { 
>  document.write(this[0]); 
> } 

如上,文件撰寫是破壞性的。

> var eArr = new ExtArray(); 
> //all three work 
> eArr.bounce(); 
> eArr.push("I am first! "); 
> eArr.first(); 

推測這是在加載事件之前運行。

> // invoking global 
> gArr.bounce(); // it works 
> gArr.push("No, it is me who is really first! "); // doesn't work 
> gArr.first(); // doesn't work 

說:「不工作」是因爲你初始化加爾你修改ExtArray.prototype之前,該位因此它具有實例方法反彈但仍然有默認的原型時,構造被宣佈。

請記住,一旦聲明完成後,該代碼在序列運行所以加爾=新ExtArray()之前ExtArray.prototype =新陣列的運行;等。

此外,一個實例有它的創建和此後不能改變(除了Mozilla的棄用屬性)即時引用構造函數的原型內部原型財產。因此,更改contsructor的原型不會改變已經構建的任何實例的內部原型。

1

您應該定義window.gArr定義ExtArray.prototype後:

function ExtArray() { 
    this.bounce = function() { 
     document.write("Bounced successfully!"); 
    }; 
} 

ExtArray.prototype = new Array; 
ExtArray.prototype.first = function() { 
    document.write(this[0]); 
}; // <-- semicolon will be REQUIRED here. 

(function() { 
    window.gArr = new ExtArray(); 
})(); 

DEMO:http://jsfiddle.net/Vg3Ze/

+0

http://jsbin.com/ewamuh/edit我試過了。它返回undefined。 :( – DrStrangeLove

+1

你忘了';'後定義ExtArray.prototype。第一 – lostyzd

+0

@DrStrangeLove:lostyzd是正確的。這將是分號將至關重要的地方。否則,你會立即*調用*'ExtArray.prototype.first'。 – user113716

相關問題