在匿名&上绑定此关键字异步功能

时间:2014-01-04 00:50:42

标签: javascript mongodb asynchronous parse-platform promise

在JavaScript中,我正在寻找一种在匿名和异步函数上使用bind()的方法。

示例:

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
    });
  }
};

我通过使函数非匿名来实现这一点,但我认为它使我的代码看起来很难看。特别是在连续有4个不同的匿名函数之后。

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);
  }
};

有更好的方法吗?

3 个答案:

答案 0 :(得分:3)

嗯,它不一定“更好”,但你可以在函数实例化表达式的右大括号之后直接调用.bind()

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

函数实例化表达式为您提供了一个函数对象引用,因此在它之后放置.并调用bind是有意义的。因此,传递给.then函数的是从.bind调用的返回值。

答案 1 :(得分:1)

此语法不正确:

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
    });
  }
};

prototype是一个对象,其属性定义为load: function() {},而不是load = 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
    });
  }
};

答案 2 :(得分:0)

一种简单的方法是将变量声明为正确的'this',并使用closuers来保持对它的引用。

exports.foo = function () {};

exports.foo.prototype = {
  load : function(id) {
    var self = this;

    var query = new Parse.Query("SomeObject");
    query.get(id).then(function(object) {
      self.object = object; // this is the wrong this
    });
  }
};
相关问题