为什么使用Function.prototype.bind而不是Function.prototype.call ?

Why use Function.prototype.bind instead of Function.prototype.call?

本文关键字:Function prototype call bind 为什么      更新时间:2023-09-26
myFunction.call(thisArg, arg1, arg2 ...)

我的理解是,当我使用call方法并提供thisArg时,函数中的this值被设置为我传递的对象。

myFunction.bind(thisArg, arg1, arg2 ...)

另一方面,bind方法返回一个新函数,并将新函数的this上下文设置为我传入的对象。

但我不明白的是为什么使用bind而不是call。如果我想做的只是改变this的上下文,那么call对我来说就足够了。那么,为什么在IE8及以下浏览器中使用bind呢?

那么,什么时候使用bind比使用call更好呢?

什么时候使用bindcall更好?

回调。

如果您需要确保在特定对象的上下文中调用函数,但无法控制函数的调用方式(例如当您将函数作为参数传递给回调时),则使用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));