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

nim*_*grg 5 javascript

myFunction.call(thisArg, arg1, arg2 ...)
Run Code Online (Sandbox Code Playgroud)

我的理解是,当我使用call方法,并提供thisArgthis在功能值反对我通过英寸

myFunction.bind(thisArg, arg1, arg2 ...)
Run Code Online (Sandbox Code Playgroud)

bind另一方面,该方法返回一个新函数,其中新函数的上下文this设置为我传入的对象.

但我不明白的是为什么用bind而不是call.如果我想做的就是改变背景this,call对我来说似乎已经足够了.那么为什么在浏览器IE8及以下版本中断时会使用bind.

那么,什么时候使用bind成为一个更好的案例相比call

zzz*_*Bov 12

什么时候使用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));
Run Code Online (Sandbox Code Playgroud)

  • 对我来说非常高兴,但根据你的例子创建这个[小提琴](http://jsfiddle.net/JZ6aS/9/)帮助我清除了这个想法.谢谢!! (2认同)