我正在阅读Chapter 2 你不知道 JS:this 和对象原型(prototype)。
假设我们有以下代码:
function foo() {
console.log(this.a);
}
var obj = {
a: 33,
foo: foo
}
var a = 22;
我理解隐式此绑定(bind):
obj.foo(); // 33
我什至理解如何将它用作回调函数使其“失去”它的 this
值:
setTimeout(obj.foo, 1000); // undefined
我不明白的是以下有关使用call()
的显式绑定(bind)的摘录和apply()
:
Unfortunately, explicit binding alone still doesn't offer any solution to the issue mentioned previously, of a function "losing" its intended this binding, or just having it paved over by a framework, etc.
我不明白为什么使用 call()
(显式绑定(bind))仍然无法解决此问题。
我尝试使用以下示例来重新创建它如何不起作用,但似乎 setTimeout
无法处理使用 call()
?它会立即触发,而不是等待 1000 毫秒。
setTimeout(foo.call(obj),1000);
<小时/>
我确实意识到使用 setTimeout(foo.bind(obj),1000);
会解决这个问题,我只是想集中精力理解书中的这段摘录。
最佳答案
It fires immediately instead of waiting 1000 ms
对,因为 .call
执行该函数。也许这样更容易理解:foo.call(obj)
与obj.foo()
完全相同。但是,setTimeout
需要传递一个函数。这就是你这么做的原因
setTimeout(obj.foo, 1000);
更早,而不是
setTimeout(obj.foo(), 1000);
那么,如果你不能使用.call
,你该如何设置this
值呢?这就是 .bind
解决的问题。它不是调用函数,而是创建一个具有绑定(bind) this
值的新函数,然后可以传递这个新函数,而不会丢失其 this
值。
相关:How to access the correct `this` context inside a callback?
<小时/>这可能不是最精确的概述,但可能有助于理解如何将 .call/.apply
和 .bind
相互关联:
+-------------------+-------------------+
| | |
| time of | time of |
|function execution | this binding |
| | |
+-------------------+-------------------+-------------------+
| | | |
| function object | future | future |
| f | | |
| | | |
+-------------------+-------------------+-------------------+
| | | |
| function call | now | now |
| f() | | |
| | | |
+-------------------+-------------------+-------------------+
| | | |
| f.call() | now | now |
| f.apply() | | |
| | | |
+-------------------+-------------------+-------------------+
| | | |
| f.bind() | future | now |
| | | |
+-------------------+-------------------+-------------------+
关于javascript - 初学者 - 显式绑定(bind) JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37487497/