How to bind a built-in anonymous function?

I am trying bind(i.e. bind(this)) a built-in anonymous callback function on object
How can this be done?

A simplified example:

var object = {

  property: function() {

    this.id = 'abc'; // 'this' binds to the object

    aFunctionWithCallback(this.id, function(data) {
      console.log(this); // null
    });
  }
};
+4
source share
1 answer

Similarly, you always use bind.

Get a reference to a function (for example, returns an expression of a function) and call a method on it bind.

aFunctionWithCallback(this.id, function(data) {
  console.log(this);
}.bind(this));
+15
source

Source: https://habr.com/ru/post/1546412/


All Articles