在JS中绑定函数而不绑定'这个'值

时间:2017-03-18 22:22:22

标签: javascript node.js

看到我们有一个像这样的简单fn:

function run(foo, cb){
   setTimeout(() => {
      cb(null, {'val': foo, 'this': this});
   }, 400);
}

我们希望重用该函数,可能使用异步库:

async.map({

foo: run.bind(null,'foo'),
bar: run.bind(null,'bar'),
baz: run.bind(null,'baz')

}, function(err){


});

我想做的是避免绑定"这个"函数中的值,并使其更简洁。

我们可以做的一件事是:

   function run(foo){
    return function(cb){
       setTimeout(() => {
          cb(null, {val: foo, this: this);
       }, 400);
    }
  }

然后有这个:

async.map({

foo: run('foo'),
bar: run('bar'),
baz: run('baz')

}, function(err){


});

这更干净,但我认为使用绑定功能可以客观地生成更多通用代码,而不是使用后一种模式。

有没有人知道是否有本地方式调用绑定而不绑定"这个"一个函数的价值。或者也许是一种实现Function.prototype.bind()函数的方法,该函数不会绑定"这个"值?

这是我的尝试:

Function.prototype.customBind = function(){

    var self = this;
    var args1 = Array.from(arguments);

    return function(){

      var args2 = Array.from(arguments);
      self.apply(this, args1.concat(args2));
   }

};

通过这种方式,我们可以使用动态值来实现"这个"?我们会像这样使用这段代码:

async.map({

foo: run.bindCustom('foo'),
bar: run.bindCustom('bar'),
baz: run.bindCustom('baz')

}, function(err){


});

0 个答案:

没有答案
相关问题