绑定范围 javascript

我试图弄清楚使用绑定的范围。我对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


翻过高山走不出你
浏览 181回答 3
3回答

波斯汪

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

LEATH

当您引用一个独立变量时,例如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()

呼啦一阵风

在 f2 中,因为它是一个不可绑定的箭头函数,x并且this.x都指向window.x.在 f1 中,x将首先尝试查找任何局部作用域变量 x,如果不能,将x在全局作用域中搜索 an 。但是因为它是绑定的,this不再指代window你绑定它的对象,所以你绑定它的对象this.x的 x 值也是如此。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript