gpt4 book ai didi

javascript - 将函数包装在闭包中的区别?

转载 作者:行者123 更新时间:2023-11-30 08:28:30 24 4
gpt4 key购买 nike

In a previous question , 我被鼓励问这个跟进:将函数 some.func 包装成类似 (arg) => some.func(arg) 有什么区别如果我知道 some.func 只接受一个参数?

作为一个具体的例子:在我的另一个问题中,我观察到使用

.on("mouseover", tip.show)

对比

.on("mouseover", (d) => tip.show(d))

在这种情况下,第一个版本确实具有预期的行为,而第二个版本的行为不同(参见 jsfiddle of other question )。这里的原因是我不小心将 tip 设为了全局。

更普遍的问题:为什么他们首先表现不同?

最佳答案

当您使用 tip.show(d) 时,该函数将被调用,传递 tip 作为 this 值。

当您使用 tip.show 作为事件监听器时,它将以当前事件目标作为 this 值被调用。

var obj = {checkThis: function(e) {
console.log(this === e.currentTarget, this === obj);
}};
document.body.addEventListener('click', obj.checkThis); // true, false
document.body.addEventListener('click', e => obj.checkThis(e)); // false, true
document.body.click();

关于javascript - 将函数包装在闭包中的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41431626/

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