25

I am trying to bind (ie bind(this)) the inline anonymous callback function to the object
How can it be done?

Simplified example:

var object = {

  property: function() {

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

    aFunctionWithCallback(this.id, function(data) {
      console.log(this); // null
    });
  }
};
2
  • 1
    How do you normally do it? Have you tried it?
    – PeeHaa
    Jun 28, 2014 at 14:24
  • Well, functionName.bind(this)(arg) but I hadn't tried it in such a case & didn't find the info, hence the question :)
    – erosman
    Jun 28, 2014 at 14:35

1 Answer 1

51

The same way you always use bind.

Get a reference to the function (such as is returned by a function expression), and call the bind method on it.

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

JS had added a new feature since this answer was written: arrow functions.

They bind this lexically instead of determining its value based on how the function is called so you can simply drop one into this code:

aFunctionWithCallback(this.id, (data) => {
  console.log(this);
});
11
  • "console.log(this); // null" ... this can never be null.
    – plalx
    Jun 28, 2014 at 14:28
  • 1
    plalx: That is what the console logged. Please note that above was a seriously simplified example. Quentin: Many thanks indeed :)
    – erosman
    Jun 28, 2014 at 14:37
  • Alternative would be to use a closure and transpiler.
    – Corey Alix
    Aug 16, 2018 at 13:52
  • @CoreyAlix — bind is a built-in function which uses a closure. I don't see how a transpiler would be relevant.
    – Quentin
    Aug 16, 2018 at 13:57
  • 3
    @CoreyAlix — They are called arrow functions, and you could use one today, but in 2014 they were rather bleeding edge.
    – Quentin
    Aug 16, 2018 at 15:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.