【发布时间】:2016-04-10 21:36:45
【问题描述】:
function FormHistory()
{
this.list = [];
this.restoreFromFile = function()
{
console.log('Restoring History From File');
fs.readFile('FormHistory.txt', function(err, data) {
if(err) throw error;
this.list = data.toString().split("\n");
});
}
}
我可以确认数据包含来自文本文件的正确信息,并且拆分正确地标记了文件。但是,由于尝试在 readFile() 的回调中引用 this.list,我似乎遇到了问题。
如何引用该列表?我必须将它传递给回调吗?
【问题讨论】:
-
将
var self = this放在外部函数中,并在回调中引用self而不是this。
标签: javascript scope callback