【问题标题】:Class scope issue [duplicate]类范围问题[重复]
【发布时间】:2018-04-27 19:24:45
【问题描述】:

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

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

this.isLoaded = !this.isLoaded

此外,由于我在这方面还很陌生,因此非常欢迎任何反馈/更正。

【问题讨论】:

  • 实际上,this 在这种情况下并不是指类。
  • @Philter 这是错误的副本。这与原型无关

标签: javascript class scope


【解决方案1】:

在课堂上尝试将arrow function 用作setInterval

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 2016-03-19
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多