为了账号安全,请及时绑定邮箱和手机立即绑定

绑定范围 javascript

绑定范围 javascript

翻过高山走不出你 2021-09-30 10:46:25
我试图弄清楚使用绑定的范围。我对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 回答

?
波斯汪

TA贡献1811条经验 获得超4个赞

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


查看完整回答
反对 回复 2021-09-30
?
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()


查看完整回答
反对 回复 2021-09-30
?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

在 f2 中,因为它是一个不可绑定的箭头函数,x并且this.x都指向window.x.

在 f1 中,x将首先尝试查找任何局部作用域变量 x,如果不能,将x在全局作用域中搜索 an 。但是因为它是绑定的,this不再指代window你绑定它的对象,所以你绑定它的对象this.x的 x 值也是如此。


查看完整回答
反对 回复 2021-09-30
  • 3 回答
  • 0 关注
  • 180 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信