[英]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 脚本解释器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.