我试图弄清楚使用绑定的范围。我对boundF1. 这里发生了什么?// console.log(x) ReferenceError: x is not defined// setting this.x - this here is global or windowthis.x = 5;console.log(x) // 5function 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
3 回答
![?](http://img1.sycdn.imooc.com/545845e900013e3e02200220-100-100.jpg)
LEATH
TA贡献1936条经验 获得超6个赞
当您引用一个独立变量时,例如console.log(x)
,解释器将尝试在外部作用域的某处找到具有相同名称的独立变量。在这里,外部作用域最终到达全局作用域,因此console.log(x)
解析为console.log(window.x)
。
性能this
也不会被添加到一个函数的变量环境; 要引用 的属性this
,您必须明确地这样做,例如:
console.log(this.x);
并不是说您应该永远使用它,而是有with
, 它可以让您像引用独立变量一样引用对象的属性(这听起来像是您认为会自动发生的事情),但强烈不建议这样做(并且在严格模式下是禁止的) )。
this.x = 5;
function f1() {
with (this) {
console.log(x); // 5
console.log(this.x); // 5
}
}
boundF1 = f1.bind({x:1});
boundF1()
![?](http://img1.sycdn.imooc.com/545862120001766302200220-100-100.jpg)
呼啦一阵风
TA贡献1802条经验 获得超6个赞
在 f2 中,因为它是一个不可绑定的箭头函数,x
并且this.x
都指向window.x
.
在 f1 中,x
将首先尝试查找任何局部作用域变量 x,如果不能,将x
在全局作用域中搜索 an 。但是因为它是绑定的,this
不再指代window
你绑定它的对象,所以你绑定它的对象this.x
的 x 值也是如此。
添加回答
举报
0/150
提交
取消