JavaScript setInterval not being properly bound to correct closure

后端 未结 3 1926
南旧
南旧 2021-01-27 02:03

Problem

Hi people, I\'m reasonably new to JavaScript and I come from the very object-oriented world of Python and Java, that\'s my disclaimer.

There are two ch

3条回答
  •  鱼传尺愫
    2021-01-27 03:01

    You lose your context of Foo in the setInterval callback. You can use Function.bind to set the context to something like this to set the context for the callback function reference back to Foo instance.

    setInterval(this.printSomething.bind(this), 3000);
    

    With the call

    setInterval(this.printSomething, 3000);
    

    The callback method gets the global context (window in case of web or global in case of tenants like node) so you don't get property bar there since this refers to the global context.

    Fiddle

    or just

     this.printSomething = function() {
         console.log(bar); //you can access bar here since it is not bound to the instance of Foo
      }
    

提交回复
热议问题