我已经将我的问题简化为以下内容:
var fs = require("fs");
var async = require("async");
var myReport;
function Report() {
this.report = null;
}
Report.prototype.initializeReport = function(callback) {
fs.readFile("./scrape reports/Scrape Report 1522604653782", "utf-8", function(err, data) {
this.report = JSON.parse(data);
console.log("Found this report: " + this.report);
callback();
});
}
module.exports = function() {
myReport = new Report();
myReport.initializeReport(function() {
console.log(myReport.report);
});
};
当我运行此功能时,输出为以下:
> Found this report: [object Object]
> null
函数oniroperizereport((能够获取JSON,但是任何尝试MyReport.Report的尝试都只能获得null,就好像从未分配过。
为什么会发生?
在您的fs.readFile
功能响应中this.report
实际上并未指向myReport
对象。因此,使用null
启动后,您从未分配给myReport.report
属性。
快速解决方案可以是:
只分配给myReport.report
而不是this.report
替代解决方案可以是:
您可以使用JavaScript的bind
或apply
函数绑定函数的上下文。