类范围问题

时间:2018-04-27 19:24:46

标签: javascript class scope

如何在回调中使我的对象属性可用?

//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)
    }
}

基本上这行不起作用,因为它无法访问我认为正确的这个

this.isLoaded = !this.isLoaded

此外,由于我对此非常新,所以非常欢迎任何反馈/更正。

1 个答案:

答案 0 :(得分:-1)

尝试在课堂上setInterval使用arrow function

  

箭头函数表达式的语法短于函数表达式,并且没有自己的this

start() {
    this._timer = setInterval( () => {
        this.isLoaded = !this.isLoaded;
    }, 1000)
}