无法读取未定义的属性“ hello”

时间:2019-05-06 10:38:30

标签: javascript scope

我有Foo和Bar两个班级。

Foo的礼貌叫你好

Bar正在使用使用属性 hello 的回调调用Foo的方法。

只要 hello 的值在Foo中发生变化,Bar所使用的值就应进行相应的同步。

但事实并非如此。我该如何重构以下代码来实现此目的?

  class Foo{
        start(){
            const bar = new Bar()
            bar.start(this.myFooCallback)
            this.hello = 'world'
        }
        myFooCallback(){
            console.log(this.hello)
        }
    }
    class Bar{
        start(cb){
            setInterval(()=>{
                cb()
            },1000)
        }
    }
    
    const foo = new Foo()
    foo.start()

1 个答案:

答案 0 :(得分:1)

您需要bind上下文:

  class Foo{
        start(){
            const bar = new Bar()
            bar.start(this.myFooCallback.bind(this))
            this.hello = 'world'
        }
        myFooCallback(){
            console.log(this.hello)
        }
    }
    class Bar{
        start(cb){
            setInterval(()=>{
                cb()
            },1000)
        }
    }
    
    const foo = new Foo()
    foo.start()

您可以了解有关上下文和函数绑定的更多信息: