2012-08-06 41 views
1

我想從深層次的嵌套匿名javascript方法調用的幾個級別的對象(類)級別設置變量值。我該怎麼做呢?在javascript中嵌套匿名方法的閉包

下面是一些代碼來解釋我正在嘗試做什麼。免責聲明:我對JavaScript中的閉包概念並不那麼舒服,所以我可能會在這裏走錯路。任何關於簡潔的方式來實現我想要做的建議將不勝感激。

// FileUtils object. 
var FileUtils = function() { 
    // Member variables. 
    this.ConfRootDir = null; 
}; 

// Method to get a file entry. 
// successCallback has to be a method with a FileEntry object. 
FileUtils.prototype.getFileEntry = function (fileName, successCallback) { 
    if (this.ConfRootDir == null) { 
     var thisObj = this; 
     // Request the root filesystem 
      // [** 1st callback, using anon method] 
     window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, 
      function (fileSystem) {       
       // Get the root directory of the file system. 
       var rootDir = fileSystem.root; 
       // Get the ConferenceToGo directory, or create if required. 
       // [** 2nd callback, using anon method] 
       rootDir.getDirectory("ConferenceToGo", { create: true, exclusive: false }, 
        function (confDir) { 
         // Set values for future use 
         // [** Definitely wrong scoping. The class level variable 
         // can't be accessed using 'this'. What to do? **] 
         this.ConfRootDir = confDir; 
         // Now try getting the handle for the list file. 
         // [** 3rd callback, using anon method. Irrelevant at this point.] 
         this.ConfRootDir.getFile(fileName, { create: false }, 
          successCallback, // Success callback [getFile] 
          function (error) { 
           logError("Unable to retrieve file: ", true, true, error); 
          }); // Failure callback [getFile] 
        }, // Success callback [getDirectory] 
        function (error) { logError("Unable to create new directory: ", true, true, error); }); // Failure callback [getDirectory] 
      }, // Success callback [requestFileSystem] 
      function (error) { logError("Problem reading file system: ", true, true, error); } 
     ); 
    } 
} 

我知道作用域(通過使用「這個」)都是錯誤的在上面的代碼,但不知道如何得到它的權利。我已經看到了一些關於綁定到上下文的答案(如this one),但我使用的是匿名方法,這使得它更難。注意:儘管我在這裏顯示的FileUtils原型中只有一個方法,但還有一些。

那些誰知道大概可以承認,我是用從科爾多瓦(PhoneGap的)庫在HTML5和JS跨平臺移動開發的方法,但在這裏,是不是真的太多有關。

+1

你可以用'thisObj',而不是'this'嵌套函數 – Esailija 2012-08-06 19:15:22

+0

@Esailija內:謝謝..試圖指出,但是並沒有完全實現。 – 2012-08-06 19:51:19

回答

1
… function() { function() { function() { … 
        // Set values for future use 
        // [** Definitely wrong scoping. The class level variable 
        // can't be accessed using 'this'. What to do? **] 
        this.ConfRootDir = confDir; 

您已經準備好了答案:thisObj.ConfRootDir。變量thisObj在嵌套函數的範圍內可用,並且仍然指向外部getFileEntry函數的this keyword,即指向FileUtils實例。

+0

哎..謝謝。我在那行(var thisObj = this;)認爲我會測試它,但在實際執行之前發射了這個問題。感覺很好,我很接近:-) – 2012-08-06 19:38:14