1

I'm trying to get a callback to work. I have tried the following 3 versions:

  //A, doesn't work
  obj.RegisterCallback(this.functionX);

  //B, still doesn't work
  _this=this;
  obj.RegisterCallback(_this.functionX);

  //C, only this works
  _this=this;
  obj.RegisterCallback( function(){ _this.functionX(); } );

Only version C works. From searching the internet, I think I understand why A doesn't work, but what's the difference between B and C ?

Thanks in advance.

b_yang
  • 109
  • 6
  • inside that `functionX`, the value of `this` is determined by *how* `functionX` is called. In (C), your code calls it as `_this.functionX()`, and so inside that function execution, `this` will be that `_this`. In the other cases `functionX` is called directly by `RegisterCallback`. Probably it does not call `functionX` with any `this` binding, and so `this` will be the global object or `undefined`. – trincot Jun 10 '20 at 20:05
  • The only difference seems to be that B get `_this.functionX` NOW and registers it for later, while C registers an anonymous function that, LATER, will get `_this.functionX`. So it may be about timing. If the value of `_this.functionX` changes between now and the time your callback is called -- such as if `_this.functionX` has not been defined yet, but it will be before the callback happens, -- then B and C will behave differently. – Cat Jun 10 '20 at 20:18

0 Answers0