将相同的上下文绑定到多个函数

时间:2015-11-06 07:01:39

标签: javascript ecmascript-6

我有一系列的承诺,我在课堂上写过:

$config['base_url'] = '';

然后我通过实例化类并运行class Executor { someFunction(){ return Promise.resolve(function(){ console.log(this.name); }); }; someOtherFunction(){ return Promise.resolve(function(){ console.log(this.date); }); }; execute(){ let {someFunction, someOtherFunction} = this; this.name = "John"; this.date = "Saturday"; someFunction=someFunction.bind(this) someFunction().then(someOtherFunction.bind(this)); } } 方法来调用:

execute

有没有更好的方法将类的上下文绑定到多个函数而不是编写多个var e = new Executor; e.execute(); 语句?

3 个答案:

答案 0 :(得分:1)

你真的不需要在这里摧毁,只会让事情变得复杂,KISS



'use strict';
class Executor {
  someFunction() {
    return new Promise((resolve, reject) =>  {
      setTimeout(() => {
        console.log(this.name);
        resolve();
      }, 250);
    });
  };

  someOtherFunction() {
    return new Promise((resolve, reject) =>  {
      setTimeout(() => {
        console.log(this.date);
        resolve();
      }, 250);
    });
  };

  execute() {
    this.name = "John";
    this.date = "Saturday";
    this.someFunction()
      .then(() => this.someOtherFunction())
      .then(() => { console.log('done!'); });
  }
}

let e = new Executor();
e.execute();




请注意,您Promise的使用情况已被破坏。

答案 1 :(得分:1)

  

有没有更好的方法将类的上下文绑定到多个函数而不是编写多个bind()语句?

引用this的值或绑定函数(请参阅How to access the correct `this` / context inside a callback?)有不同的方法,但是一次绑定多个函数的简写存在。

答案 2 :(得分:1)

这种方法可能会或可能不会让您感到兴奋。我们在context上定义Promise方法以将上下文附加到promise,并使用thenWithContext方法执行then方法,并自动绑定传入的处理程序。

Object.defineProperties(Promise.prototype, {

  context: { value: function(context) { this.context = context; return this; } },

  thenWithContext: { value: function(resolve, reject) {
    return this.then(
      (...args) => typeof resolve === 'function' && resolve.call(this.context, ...args),
      (...args) => typeof reject  === 'function' && reject.call (this.context, ...args)
    ).context(this);
  } }

});

用法:

execute() {
  this.someFunction() . context(this) . thenWithContext(this.someOtherFunction);
}