Skip to content Skip to sidebar Skip to footer

How To Reference Properties Of A Class From Within A Callback

Given the following class: class TimerFunk { constructor(someObject){ this.a = 1 this.someObject = someObject } funk(){ console.log(this.a)

Solution 1:

Your callback is called without the TimerFunk instance t as the this object:

function(callback){callback()}}

A solution is to bind the this object of the callback to the TimerFunk instance:

funk() {
  ...
  this.someObject.execCallback(this.funk.bind(this));
}

Alternatively, you can explicitly pass t as the this object via callback.call(t):

t = new TimerFunk({execCallback:function(callback){callback.call(t)}});

Post a Comment for "How To Reference Properties Of A Class From Within A Callback"