我正在尝试从嵌套匿名 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”)是错误的,但不知道如何正确。我已经看到了一些关于绑定(bind)到上下文的答案(例如 this one ),但我使用的是匿名方法,因此这使得它变得更加困难。注意:虽然我在这里只展示了 FileUtils 原型(prototype)中的一种方法,但还有更多方法。
那些了解的人可能会认识到我正在使用 cordova (PhoneGap) 库中的方法来进行 HTML5 和 JS 中的跨平台移动开发,但这与这里无关。
最佳答案
… 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
变量在嵌套函数的范围内可用,并且仍然指向 this
keyword外部 getFileEntry
函数的,即 FileUtils
实例。
关于javascript - javascript 中嵌套匿名方法的闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11834356/