gpt4 book ai didi

javascript - 无法读取未定义的属性 'hello'

转载 作者:行者123 更新时间:2023-12-02 23:42:37 25 4
gpt4 key购买 nike

我有两个类 Foo 和 Bar。

还有 Foo 的礼节叫你好

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

每当 Foo 中的 hello 值发生变化时,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()

最佳答案

您需要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()

您可以阅读有关上下文和函数绑定(bind)的更多信息:

关于javascript - 无法读取未定义的属性 'hello',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56003488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com