0

I have two classes Foo and Bar.

And propriety of Foo called hello.

Bar is calling a method of Foo using a callback which uses the property hello.

Whenever the value of hello changes in Foo, the value utilized by Bar should synchronize accordingly.

But it doesn't. How can I refactor the below code to achieve this?

  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()
TSR
  • 9,145
  • 14
  • 51
  • 114
  • [setTimeout fails to bind to “this” prototype function](https://stackoverflow.com/questions/31955836) and [Pass correct “this” context to setTimeout callback?](https://stackoverflow.com/questions/2130241) – adiga May 06 '19 at 11:02

1 Answers1

1

You need to bind a context:

  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()

You can read more about context and function binding:

falinsky
  • 6,305
  • 3
  • 25
  • 50