首页 > 解决方案 > bind vs apply:这两者有区别吗?

问题描述

考虑以下函数:

function bind(fn, context) {
  return function() {
    return fn.apply(context, arguments);
  }
}

这个函数做的事情和 完全一样Function.prototype.bind吗?

即,给定上面的函数定义,下面两行代码是否应该实现完全相同的事情?

boundFunction = bind(someFunction, someContext);

// same same?

boundFunction = someFunction.bind(someContext);

如果有任何微妙或不那么微妙的差异,它们是什么?

(我问,因为我看到上面定义的函数在一些 JavaScript 中使用,我想知道为什么他们不简单地使用Function.prototype.bind.)

标签: javascriptbindapply

解决方案


因此,基于评论,这似乎是答案:

在我的示例中,这两行...

boundFunction = bind(someFunction, someContext);
boundFunction = someFunction.bind(someContext);

...确实达到了相同的结果。

但是,以这种方式定义的“绑定”函数不提供绑定更多参数的可能性,就像Function.prototype.bind这样,即:

function abc(a, b, c) {
  console.log('a: '+a, 'b: '+b, 'c: '+c);
}

// This function predefines the first argument for abc:
var bc = abc.bind(undefined, 'Ay!');
abc('Yo!', 'hello', 'world');
// a: Yo! b: hello c: world
bc('hello', 'world');
// a: Ay! b: hello c: world

推荐阅读