0

My program contains a method that is passed a callback function. This callback function may be within another object. Here is a rough snipped (may not be proper JavaScript, just to get an idea):

var myobj = {
  f1: function(callback) {
  var hr = new XMLHttpRequest;
  hr.onload = callback.bind(this);
  },

  f2: function() {
    this.f1(this.f3);
  },

  f3: function(event) {
  }
}

In this case, writing this as parameter to callback.bind works. However, think of another object:

var theirobj = {
  f4: function() {
    myobj.f1(this.f3);
  },

  f5: function(event) {
  }
}

Now, it does not work anymore, because this refers to myobj, but callback refers to a functon in theirobj.

So, the bind used to assign the onload event handler of XMLHttpRequest needs the object variable of the callback function. Is there something like callback.getInstanceVariable() or callback.instance in the Function prototype? How can get this reference?

rexkogitans
  • 279
  • 2
  • 17
  • 2
    Bind when passing the callback to `f1`! `this.f1(this.f3.bind(this))` `f1` shouldn't need to and in fact *can't* worry about this. – deceze Sep 12 '19 at 09:54
  • @deceze Great and fast! If you turn your comment into answer, I'll accept it. Also, is this really a duplicate? I saw the other post before I posted my question, but I could not see how the question describes my problem. – rexkogitans Sep 12 '19 at 10:02

0 Answers0