【问题标题】:bind() on promise error function - javascript承诺错误函数上的 bind() - javascript
【发布时间】:2016-06-10 02:31:14
【问题描述】:

我找到了这个coden-p。有人可以在这种情况下解释.bind(this) 的目的吗?我们现在可以在哪里访问this?在已解决的承诺中?

get: function(endpoint, params, callback) {
  var cb = callback || angular.noop;
  var deferred = $q.defer();

  $http.get(
    endpoint,
    params
  ).
  success(function(data) {
    deferred.resolve(data);
    return cb();
  }).
  error(function(err) {
    deferred.reject(err);
    return cb(err);
  }.bind(this));

  return deferred.promise;
}

【问题讨论】:

    标签: javascript promise bind angular-promise angular-http


    【解决方案1】:

    函数对象的bind(newContext)方法的目的是返回一个以上下文this作为第一个参数传递给bind()的新函数。

    例如:

    var message = {text: 'I am the context'};
    
    function tryMe() {
      console.log(this);
    }
    
    tryMe(); // will print undefined (in strict mode) or global object
    tryMe.bind(message)(); // will print '{text: 'I am the context'}'
    

    在您的示例中,使用bind() 的想法是在错误处理程序中保留get() 方法的上下文this

    .error(function(err) {
        deferred.reject(err);
        //now use this.get() for example
        return cb(err);
      }.bind(this));
    

    但是在处理程序中没有调用与新上下文关联的方法。

    Gentle explanation of this查看更多详情。

    【讨论】:

      猜你喜欢
      • 2016-12-06
      • 2016-03-02
      • 2017-12-18
      • 1970-01-01
      • 2021-01-08
      • 2016-11-11
      • 2017-12-18
      • 2018-09-07
      • 2015-08-13
      相关资源
      最近更新 更多