JavaScript utilises async paradigm a lot, so when you read file for example - function you provide as callback will be executed in own scope. this
is related to scope, so you will lose it. After you are trying to reference this.testData
will actually not reference DataProvider object, but scope of anonymous function you've provided to parseString.
So there are few ways to overcome, and easiest here would be persist this
in variable in upper scope, so you can reference it, call it for example self
, some devs prefer that
.
var DataProvider = function(dataPath) {
this.dataPath = dataPath;
this.testData;
var self = this;
fs.readFile(this.dataPath, function(err, data) {
var parser = new xml2js.Parser();
parser.parseString(data, function(err, result) {
//console.log(util.inspect(result, false, null));
self.testData = result;
});
});
};
Or by using .bind
, but dissadvantage here is that it has to be used twice (as you have two scopes to 'travel' through:
var DataProvider = function(dataPath) {
this.dataPath = dataPath;
this.testData;
fs.readFile(this.dataPath, function(err, data) {
var parser = new xml2js.Parser();
parser.parseString(data, function(err, result) {
//console.log(util.inspect(result, false, null));
this.testData = result;
}.bind(this));
}.bind(this));
};