javascript - 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
.)
解决方案
因此,基于评论,这似乎是答案:
在我的示例中,这两行...
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
推荐阅读
- c++ - 类中的恒容量向量
- node.js - 如何在服务nestjs中模拟getMongoRepository
- r - 创建一个包含计算字段的新表,其中包含来自两个不同表的数据
- angular - Angular/Material mat-form-field input - 茉莉花单元测试中的浮动标签问题
- google-maps - 如何在 Flutter Web 中使用谷歌地图库?
- firebase - Firestore 是否有 Dart 接口 - 使用 https://firebase.google.com/docs/firestore/quickstart 中的 API?
- php - 单击时将相同的值设置为另一个字段
- javascript - 覆盖本地文件的简单而优雅的方法如果存在?
- javascript - 有什么方法可以垂直拆分堆叠条的一部分?
- amazon-web-services - 如何从当前时间戳生成 1 年中每一天的每一小时的序列