【问题标题】:binding this keyword on anonymous & async function在匿名和异步函数上绑定 this 关键字
【发布时间】:2014-01-04 00:50:42
【问题描述】:

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

有没有更好的办法?

【问题讨论】:

    标签: javascript mongodb asynchronous parse-platform promise


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      此语法不正确:

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

      【讨论】:

      • 固定语法。谢谢!
      【解决方案3】:

      一个简单的方法是为正确的“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
          });
        }
      };
      

      【讨论】:

        猜你喜欢
        • 2011-02-11
        • 1970-01-01
        • 1970-01-01
        • 2019-01-10
        • 2023-04-04
        • 2011-06-27
        • 2012-03-22
        • 2019-02-01
        • 2012-05-10
        相关资源
        最近更新 更多