javascript - 在 javascript 中使用 promise 和原型(prototype)时优雅的回调绑定(bind)

标签 javascript prototype promise

我是重度 JavaScript 原型(prototype)和 promise 用户。

我的问题是我需要使用 .bind(this) 来设置每次我然后验证我的 promise 时的正确上下文。

这是显示问题的示例代码 (jsbin):

var Q = require('Q');

var AsyncCounter = function(initialValue){
  this.value = initialValue;
};

AsyncCounter.prototype.increment=function(){
  return Q.fcall(function(){
    return ++this.value;
  }.bind(this));
};

AsyncCounter.prototype.decrement=function(){
  return Q.fcall(function(){
    return --this.value;
  }.bind(this));
};

var counter = new AsyncCounter(10);

counter.increment()
  .then(function(incrementedValue){
    console.log('incremented value:', incrementedValue)
  })
  .then(counter.decrement.bind(counter))
  .then(function(decrementedValue){
    console.log('decremented value:', decrementedValue)
  });

看看我必须多久依赖一次 bind()?我觉得太不雅观了。

我确实知道 petkaantonov/bluebird promise 库及其非常有用 bind(scope)函数在回调上传播范围,但我觉得有更好的本地方法来做到这一点。

有没有人有正确的方法来做到这一点?

最佳答案

还记得当您了解 Foo.prototype.bar=function(){...} 并拒绝在构造函数中定义方法时 this.bar = function() {...}?原因是速度和内存效率。

好吧,现在您有充分的理由让时光倒流并牺牲速度/效率,以实现“可分离”方法 - 即特定于它们的构造函数实例的方法,这个 ready bound,这正是你想要的。

如果多次调用这些方法,那么在引用函数时不必使用 bind() 就可以弥补构造的低效率。此外,您还可以获得所需的句法便利。

这里是您的示例的一个版本,经过重新调整以更好地展示语法的便利性:

var AsyncCounter = function(value){

    this.increment = function(){
      return Q.fcall(function(){
        return console.log("++value: " + ++value);
      }.bind(this));
    }.bind(this);

    this.decrement = function(){
      return Q.fcall(function(){
        return console.log("--value: " + --value);
      }.bind(this));
    }.bind(this);
};

var counter = new AsyncCounter(10);

counter.increment()
  .then(counter.decrement)
  .then(counter.increment);

总而言之,您需要做两件事:

  • 在构造函数内部定义方法
  • this 绑定(bind)到方法。

关于javascript - 在 javascript 中使用 promise 和原型(prototype)时优雅的回调绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26056188/

相关文章:

Javascript Ajax 调用不起作用?

javascript - 更改 ES6 构造函数中键的值

javascript - 处理类内的事件(原型(prototype))

javascript - promise 回调是否发送到事件队列?

javascript - Dojo promise 一切——但这需要等待所有 promise 的返回

javascript - 添加高亮效果,css float

javascript - Jquery/Javascript 中的 Post/Get 处理程序

javascript - 如何处理 JavaScript 中的嵌套 Promise?

javascript - AngularJS:如何使这个自动收报机动画连续并动态获取元素尺寸

javascript - 使用原型(prototype)访问对象属性