javascript中嵌套匿名方法的闭包
我试图从嵌套的匿名javascript方法调用的几个层次中,在对象(类)级别设置一个变量值。我该怎么做 这里有一些代码来解释我要做的事情。免责声明:我对javascript中的闭包概念不太熟悉,所以我可能走错了路。任何关于以简洁的方式实现我想做的事情的建议都将不胜感激javascript中嵌套匿名方法的闭包,javascript,closures,anonymous-methods,Javascript,Closures,Anonymous Methods,我试图从嵌套的匿名javascript方法调用的几个层次中,在对象(类)级别设置一个变量值。我该怎么做 这里有一些代码来解释我要做的事情。免责声明:我对javascript中的闭包概念不太熟悉,所以我可能走错了路。任何关于以简洁的方式实现我想做的事情的建议都将不胜感激 // FileUtils object. var FileUtils = function () { // Member variables. this.ConfRootDir = null; }; // Met
// 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”)都是错误的,但不确定如何使其正确。我已经看到了一些关于绑定到上下文的答案(比如),但我使用的是匿名方法,这使得绑定更加困难。注意:虽然我在这里只展示了FileUtils原型中的一个方法,但还有一些方法
那些知道的人可能会认识到,我在HTML5和JS中使用的是cordova(PhoneGap)库中用于跨平台移动开发的方法,但这在这里并不重要
… 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
函数的作用域,即指向FileUtils
实例
您已经准备好了答案:
thisObj.ConfRootDir
。thisObj
变量在嵌套函数的作用域中可用,并且仍然指向外部的getFileEntry
函数,即FileUtils
实例。您可以在嵌套函数中使用thisObj
而不是this
functions@Esailija:谢谢。。正在尝试,但未完全实现。您可以在嵌套的functions@Esailija:谢谢。。我试过了,但没有完全实现。哎呀。。谢谢我在那行(var thisObj=this;)中放了一行,以为我会测试它,但在实际操作之前就抛出了这个问题。感觉很好,我离得很近:-)哎呀。。谢谢我在那行(var thisObj=this;)中放了一行,以为我会测试它,但在实际操作之前就抛出了这个问题。感觉很好,我很接近:-)