2011-06-24 144 views
3

我正在寫一些Javascript代碼使用jQuery在瀏覽器中顯示特殊格式的小部件。我已經取得了成功,但現在我正在努力重構我的代碼,原因有兩個。範圍問題嵌套的Javascript對象

(1)我希望能夠不止一次地輕鬆使用這個小部件,並且有一個引用每個小部件的Javascript對象。 (2)我希望以正確的方式做到這一點,以便我的代碼完全可重用,並且不會帶有各種對象和函數的全局名稱空間。

我有一個範圍界定問題,我希望解決這個問題並提高我對Javascript範圍的理解。我已經凝聚這個問題降低到一個很小的代碼片段,說明我在做什麼:

function getMyObject() { 
     var theObject = { 
      doThis: function() { }, 
      doThat: function() { }, 
      combinations: { 
       doThisTwice: function() { doThis(); doThis(); }, 
       doThatTwice: function() { doThat(); doThat(); } 
      } 
     }; 
     return theObject; 
    } 

    var myObject = getMyObject(); 
    myObject.combinations.doThisTwice(); 

我宣佈,返回一個對象的功能。

但是,當我嘗試執行函數combinations.doThisTwice()時,程序會拋出一個錯誤,指出doThis()超出了範圍。我如何參考combinations.doThisTwice範圍內的功能doThis

更新:衷心感謝你的回答我的問題:與theObject.doThis()功能doThisTwice()內更換doThis()。這有效,但我不明白爲什麼。

我會認爲名稱theObject將不會有效,直到對象聲明結束。我想我必須誤解Javascript的一些基本方面......可能是因爲C語法。

+0

是的,JS很奇怪。 Google爲Javscript範圍和關閉。您將更清楚地瞭解範圍的工作原理。 – Mrchief

回答

2

你需要做的:

function getMyObject() { 
    var theObject = { 
     doThis: function() { }, 
     doThat: function() { }, 
     combinations: { 
      doThisTwice: function() { theObject.doThis(); theObject.doThis(); }, 
      doThatTwice: function() { theObject.doThat(); theObject.doThat(); } 
     } 
    }; 
    return theObject; 
} 

VAR myObject的= getMyObject(); myObject.combinations.doThisTwice();

您從外部範圍引用'theObject'以調用內部對象中的函數。

+0

你打敗了我! – Mrchief

+0

我很快就這樣;) –

+0

嘗試從'theObject'繼承原型或將'theObject'複製到另一個變量,它不再工作。如果你只是通過變量引用對象,爲什麼你首先需要'this'? – Gherman

2

doThis未在函數範圍中定義,因此它將遍歷作用域鏈,但找不到它。

您可以通過

theObject.doThis(); 

然而,更可讀的參考,如果你定義你的函數一樣,這可能是:

function getMyObject() { 
     function doThis() {}; 
     function doThat() {}; 

     var theObject = { 
      doThis: doThis, 
      doThat: doThat, 
      combinations: { 
       doThisTwice: function() { doThis(); doThis(); }, 
       doThatTwice: function() { doThat(); doThat(); } 
      } 
     }; 
     return theObject; 
    } 

但是在這種情況下,當你從外部改變doThisdoThisTwice仍然會引用原始功能。

0

doThisTwice,使用theObject.doThis();代替doThis();