Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binding this keyword on anonymous & async function

In JavaScript I am looking for a way to use bind() on an anonymous and async function.

Example:

exports.foo = function () {};

exports.foo.prototype = {
  load : function(id) {
    var query = new Parse.Query("SomeObject");
    query.get(id).then(function(object) {
      this.object = object; // this is the wrong this
    });
  }
};

I got this working by making the functions non-anonymous, but I think it makes my code look ugly. Especially after having 4 different anonymous functions in a row.

exports.foo = function () {};

exports.foo.prototype = {
  load : function(id) {

    function _load(object) {
      this.object = object;
    }
    var _loadThis = _load.bind(this);

    var query = new Parse.Query("SomeObject");
    query.get(id).then(_loadThis);
  }
};

Is there a better way?

like image 927
Diamonds Avatar asked Aug 13 '26 19:08

Diamonds


2 Answers

Well it's not necessarily "better", but you can call .bind() directly after the closing brace of your function instantiation expression:

query.get(id).then(function(object) {
  this.object = object; // this is the wrong this
}.bind(this));

A function instantiation expression gives you a function object reference, so putting a . after it and calling bind makes sense. What gets passed to the .then function, therefore, is the return value from the call to .bind.

like image 170
Pointy Avatar answered Aug 16 '26 09:08

Pointy


This syntax is not correct:

exports.foo.prototype = {
  load = function(id) {
    var query = new Parse.Query("SomeObject");
    query.get(id).then(function(object) {
      this.object = object; // this is the wrong this
    });
  }
};

The prototype is an object who's properties are defined as load: function() {}, not load = function() {}.

It should be:

exports.foo.prototype = {
  load: function(id) {
    var query = new Parse.Query("SomeObject");
    query.get(id).then(function(object) {
      this.object = object; // this is the wrong this
    });
  }
};
like image 23
jfriend00 Avatar answered Aug 16 '26 08:08

jfriend00