Thursday, 13 October 2016

javascript - Class scope issue

How do I make my objects property available within the callback?



//entrypoint.js

var DeviceManager = require('./class')
DM = new DeviceManager()

DM.start();

var t = setInterval(function() {
console.log("Module.isLoaded = " + DM.isLoaded);
}, 500);
setTimeout(function() {
console.log("Stopping");

clearInterval(t);
DM.stop();
}, 10000);


//class.js
module.exports = class DeviceManager {
constructor(){
this.isLoaded = false;
this._timer= null;

}

start(){

console.log('starting timer')
this._timer = setInterval( function() {
console.log('timer callback')
this.isLoaded = !this.isLoaded;
},1000)


}

stop() {
console.log('stopping timer')
clearInterval(this._timer)
}
}


Basically this line doesnt work, because it doesnt have access to the correct this I assume.




this.isLoaded = !this.isLoaded


Also, since im all around pretty new at this, any feedback/corrections are very welcome.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...