【问题标题】:bind vs apply: Is there a difference between these two?bind vs apply:这两者有区别吗?
【发布时间】:2018-05-25 17:56:16
【问题描述】:

考虑以下函数:

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。)

【问题讨论】:

  • 您的版本忽略了进一步的参数。
  • 他们可能针对的是旧版浏览器。
  • 您的两行代码是相同的,但是用户定义的bind() 的这个定义不允许绑定参数在传入参数之前,如原型bind() 方法。

标签: javascript bind apply


【解决方案1】:

所以,在 cmets 的基础上,这似乎是答案:

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

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

【讨论】:

    猜你喜欢
    • 2014-03-26
    • 2015-06-05
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    相关资源
    最近更新 更多