简体   繁体   English

javascript中的变量声明(全局与本地)

[英]variable declaration in javascript(global vs local)

I'm not able to understand the following code我无法理解以下代码

function test() {
  let a = b = 0;
  a++;
  return a;
}

test();
typeof a;
typeof b;

getting type of a as undefined whereas typeof b as "number"将 a 的类型设为未定义,而将 b 的类型设为“数字”

The main difference is scoping rules.主要区别在于范围规则。 variables that are declared by the keyword var are scoped to the immediate function body while let variables are scoped to the immediate enclosing block denoted by { }, meaning blocker scoped.由关键字 var 声明的变量的作用域是立即的 function 主体,而 let 变量的作用域是由 { } 表示的直接封闭块,这意味着阻塞器作用域。 This is the reason why let keyword was introduced to the language.这就是为什么在语言中引入 let 关键字的原因。 the function scope can be very confusing and can cause many bugs in JavaScript. function scope 可能非常混乱,并可能导致 JavaScript 中的许多错误。

So, what you're seeing in the code is a decleration of let a that makes it scoped to the function.因此,您在代码中看到的是对 let a 的声明,使其范围为 function。 hence, the typeof a outside of the function is indeed undefined (since that area of code is not aware of a).因此,function 之外的 a 类型确实是未定义的(因为该代码区域不知道 a)。 b, on the other hand, is not declared with let.另一方面,b 不是用 let 声明的。 it's being assigned to the number 0, meaning it's an implicit global variable, hence existing out of the function.它被分配给数字 0,这意味着它是一个隐式全局变量,因此存在于 function 之外。

Here when the foo() function executions starts java script interpreter这里当 foo() function 执行开始时 java 脚本解释器

  1. creates variable a in the scope of f00() function在 f00() function 的 scope 中创建变量 a
  2. for variable b the interpreter thinks it is accidentally created so the interpreter creates a global variable b and assigns value 0 eg: (window.b = 0; or b = 0;) this is because scoping rules here var keyword will be scoped to the immediate variable store (eg: a) so对于变量 b解释器认为它是意外创建的,因此解释器创建一个全局变量 b 并赋值 0 例如: (window.b = 0; or b = 0;)这是因为这里的作用域规则 var 关键字将作用于立即变量存储(例如:a)所以
  3. type of variable a is undefined as it is in the scope of function foo()变量 a 的类型未定义,因为它在 function foo() 的 scope 中
  4. type of variable b is number as it is global variable and is available anywhere in the code变量 b 的类型是数字,因为它是全局变量,并且可以在代码中的任何位置使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM