gpt4 book ai didi

javascript - 为什么需要 JavaScript bind()?

转载 作者:IT王子 更新时间:2023-10-29 03:06:59 24 4
gpt4 key购买 nike

示例 1 中的问题是“this”指的是全局名称而不是 myName 对象。

我理解bind()在设置this的值到特定对象时的使用,所以它解决了示例1中的问题,但是为什么首先会出现这个问题呢?它只是创建 Javascript 的方式吗?

我也想知道为什么示例 3 解决了问题以及示例 2 和示例 3 之间的区别。

this.name = "John"

var myName = {
name: "Tom",
getName: function() {
return this.name
}
}

var storeMyName = myName.getName; // example 1
var storeMyName2 = myName.getName.bind(myName); // example 2
var storeMyName3 = myName.getName(); // example 3

console.log("example 1: " + storeMyName()); // doesn't work
console.log("example 2: " + storeMyName2()); // works
console.log("example 3: " + storeMyName3); // works

最佳答案

Why is JavaScript bind() necessary?

this 的值由如何函数被调用决定。如果调用该函数的是,那么通常不需要使用.bind,因为您可以控制如何调用该函数,因此也可以控制它的这个值。

但是,通常不是您调用该函数。函数作为回调和事件处理程序传递给其他函数。它们由其他代码调用,您无法控制如何函数被调用,因此无法控制this 将引用什么。

如果您的函数需要将 this 设置为特定值,而您不是调用该函数的人,则需要将函数.bind 设置为特定的 this 值。

换句话说:.bind 允许您设置 this 的值,而无需 now 调用函数。

这里是引用/调用函数的比较:

                    +-------------------+-------------------+
| | |
| 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 |
| | | |
+-------------------+-------------------+-------------------+

I'm also wondering why example 3 solves the issue and the difference between example 2 and 3.

示例 1/2 和示例 3 截然不同。 storeMyNamestoreMyName2 包含将来调用的函数,而 storeMyName3 包含调用 myName.getName() 在那一刻


进一步阅读 Material :

关于javascript - 为什么需要 JavaScript bind()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41391288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com