为什么使用Function.prototype.bind而不是Function.prototype.call ?
Why use Function.prototype.bind instead of Function.prototype.call?
myFunction.call(thisArg, arg1, arg2 ...)
我的理解是,当我使用call
方法并提供thisArg
时,函数中的this
值被设置为我传递的对象。
myFunction.bind(thisArg, arg1, arg2 ...)
另一方面,bind
方法返回一个新函数,并将新函数的this
上下文设置为我传入的对象。
但我不明白的是为什么使用bind
而不是call
。如果我想做的只是改变this
的上下文,那么call
对我来说就足够了。那么,为什么在IE8及以下浏览器中使用bind呢?
那么,什么时候使用bind
比使用call
更好呢?
什么时候使用
bind
比call
更好?
回调。
如果您需要确保在特定对象的上下文中调用函数,但无法控制函数的调用方式(例如当您将函数作为参数传递给回调时),则使用bind
。
var f,
example;
f = new Foo();
example = document.getElementById('example');
//`f.bar` is called in the context of `f`
f.bar();
//`f.bar` will be called in the context of `example`
example.addEventListener('click', f.bar);
//`f.bar` will be called in the context of `f`
example.addEventListener('click', f.bar.bind(f));
相关文章:
- 直接在函数声明上使用function.prototype.bind
- 如何通过 Function.prototype.apply() 更改调用函数的参数
- Function.prototype.call和Function.protoype.all只应用一个参数
- requestAnimationFrame的Function.prototype.bind导致属性不可读
- 对象如何获取 Function.prototype 方法
- Function.prototype上调用方法的性质
- 为什么在Function.prototype上没有原型属性
- Function.prototype.propertyname === Object.propertyname is t
- Function.prototype.apply:参数列表的类型错误
- node.js 使用 function.prototype.apply 执行的泛型函数
- Snippet usefulness - Function.prototype.call.bind(Function.p
- 使用 Function.prototype.bind.apply(Obj, args) 将参数传递给对象,只传递第一个元
- Function.prototype.call.bind 是如何工作的
- 在 Function.prototype.method 中返回它有什么作用
- JavaScript 中 Function.prototype 和 Object.prototype 之间的区别
- 使用 Function.prototype.bind 或保存的引用
- Phantomjs Function.prototype.bind
- Function.prototype.bind with null 作为参数
- Function.prototype.toMethod() 是做什么的
- Function.prototype.method what is prototype[name]