为什么外部作用域变量没有正确地绑定到内部变量? [英] Why doesn't the outer scope variable get properly bound to the inner variable?

查看:29
本文介绍了为什么外部作用域变量没有正确地绑定到内部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(function(){
  var x = 23;
  return function(){
    var x = x;
    return x;
  }
}())();

为什么它返回undefined而不是23?

Why does it return undefined instead of 23?

不应该var x = x;部分足够明确,因为右侧隐式指的是外部范围中的x?

Shouldn't the var x = x; part be sufficiently unambiguous because the right hand side implicitly refers to the x in the outer scope?

推荐答案

语句 var x = x; 从外部范围看不到变量 x .范围内的变量 x 在赋值之前已经存在,并且从外部范围隐藏该变量.

The statement var x = x; doesn't see the variable x from the outer scope. The variable x inside the scope already exists before the assignment, and shadows the variable from the outer scope.

作用域中的所有变量都是在作用域代码执行(提升)之前创建的,因此与您具有的作用相同:

All variables in the scope are created before the code in the scope executes (hoisted), so it's the same as if you had:

(function(){
  var x;
  x = 23;
  return function(){
    var x;
    x = x;
    return x;
  }
}())();


实际上,在变量中声明变量的位置并不重要.您可以在代码中最后声明它们(尽管这会有些混乱),并且代码仍然可以正常工作:


It actually doesn't matter where in the scope you declare the variables. You can declare them last in the code (although that would be a bit confusing), and the code still works the same:

(function(){
  x = 23;
  return function(){
    x = x;
    return x;
    var x;
  }
  var x;
}())();

这篇关于为什么外部作用域变量没有正确地绑定到内部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆