myFunction.call(thisArg, arg1, arg2 ...)
Run Code Online (Sandbox Code Playgroud)
我的理解是,当我使用call方法,并提供thisArg了this在功能值反对我通过英寸
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)
| 归档时间: |
|
| 查看次数: |
1139 次 |
| 最近记录: |