gpt4 book ai didi

javascript - 绑定(bind)范围 javascript

转载 作者:太空宇宙 更新时间:2023-11-04 03:00:34 24 4
gpt4 key购买 nike

我正在尝试找出使用绑定(bind)的范围。我对 boundF1 的输出感到困惑。这是怎么回事?

// console.log(x) ReferenceError: x is not defined

// setting this.x - this here is global or window
this.x = 5;
console.log(x) // 5

function f1() {
console.log(x); // 5
console.log(this.x); // 5
}

// Lexically bound this to window
f2 = () => {
console.log(x); // 5
console.log(this.x); // 5
}

f1()
f2()

boundF1 = f1.bind({x:1});
boundF2 = f2.bind({x:1});


boundF1() // 5 1 Why is this not 1, 1. How is x resolved here? Does it check local vars, then global vars. Would it ever use this? What is the scoping rule?

boundF2() // 5 5

最佳答案

因为x将始终在范围内查找变量。它与this(上下文)无关。当您调用 .bind 时,您只需在函数内部设置 this 的值。

关于javascript - 绑定(bind)范围 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57725077/

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