我有一个脚本,其中包含一个使用回调返回状态的函数,并且我必须将其是否成功提交给类变量。我无法使用 this
来访问它,因为它不在范围内。我无法发布我的确切代码的代码片段,但以下内容应该说明我的问题
var thisObject = Item.prototype;
function Item(directory){
this._completedTasks = [];
this._fsDirectory = directory;
if (!fs.existsSync(this._fsDirectory)){
fs.mkdirSync(this._fsDirectory);
}
}
thisObject.doStuff = function(url){
goGetFile(url, function(message){
this._completedTasks.push(url);
//_completedTasks appears to be undefined here.
});
}
module.exports = Item;
如何访问变量_completedTasks
?
最佳答案
您可以做两件事,保存对 this
的引用,然后使用它,或者使用 bind设置执行上下文
//Saving a reference
thisObject.doStuff = function(url){
var that = this;
goGetFile(url, function(message){
that._completedTasks.push(url);
});
}
//Using bind
thisObject.doStuff = function(url){
goGetFile(url, function(message){
this._completedTasks.push(url);
}.bind(this));
}
关于javascript - 如何调用 'upper class'这个关键字呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27612893/