2012-08-06 56 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