I'm trying to create a class in node.js for a small project of mine but I can't really figure out how scoping works.
I have a basic constructor function:
function testClass(username){
this.config = {
uName : username,
url : 'url_prefix'+username,
};
this.lastGame = {
firstTime : 1,
time : null,
outcome: null,
playingAs: null,
playingAgainst : null,
};
this.loadProfile(this.config['url']);
};
And the loadProfile function:
testClass.prototype.loadProfile = function(url){
request(url,function(error,response,body){
$ = cheerio.load(body);
matchTable = $('div[class=test]').children();
tempLast = matchTable.first().html();
if(this.config['firstTime'] == 1 || this.lastGame['time'] != tempLast){
this.lastGame['time'] = tempLast;
}
});
};
(I'm using the Request and Cheerio libraries.)
The problem I have is that I can't use the class variables using "this" inside the "request" function.
It returns "Cannot read property 'firstTime' of Undefined".
This only happens inside the "request" function. I can use "this" and all its functions/variables just fine outside it.
I've thought about passing it to the function but a) I couldn't find how and b) That would mean that any modification I made to the variables wouldn't change the actual class variables.
Could anyone please explain what is going on?
Thanks a lot!