我正在尝试找出使用绑定(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/