javascript - 在 Javascript 中,我可以在变量声明之前使用它吗?

标签 javascript variables scope switch-statement

我一直在想是否可以在定义之前在JS中使用变量, 例如:

var country = "USA";
switch (country) {
    case "USA":
        country = i;
    case "blach":
        //not finished yet
}
/*
  put a whole
  bunch more code here
*/
var i = 10;

这有效吗?允许吗?如果是这样,它的技术术语是什么?

最佳答案

这是 JavaScript 引擎使用的一种技术,称为 hoisting .解析器将在运行之前通读整个函数,并且任何变量声明(即使用 var 关键字)都将被执行,就好像它们位于包含范围的顶部一样。所以你的代码表现得像:

var country;
var i;

country = "USA";
switch (country) {
case "USA":
    country = i;
case "blach":
    //not finished yet
}

i = 10;

因此,i 在整个范围内声明,但它的值是未定义,直到 i = 10 语句运行。

在 ECMAScript 术语中,当一个函数被调用时,该函数的新词法作用域会在该函数的任何代码运行之前构建它的 VariableEnvironment。在 ECMAScript 10.5, step 8 :

8. For each VariableDeclaration... d in code, in source text order do

a. Let dn be the Identifier in d.

...

i. Call env’s CreateMutableBinding concrete method passing dn and configurableBindings as the arguments.

ii. Call env’s SetMutableBinding concrete method passing dn, undefined, and strict as the arguments.

这很啰嗦,但基本上是这样说的:

Before you run a function, look through the function's source code for declarations like var [identifierName].

For each declaration you find, create a new variable in the function's scope with the name [identifierName] used in the declaration and then set its value to undefined

关于javascript - 在 Javascript 中,我可以在变量声明之前使用它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20220862/

相关文章:

JavaScript 事件处理程序 - 为什么没有警报?

javascript - document.getElementById 不会设置变量

javascript - google.setOnLoadCallback 在 jquery ajax 成功函数中带有参数

ios - 是否可以在UITextView中使用变量?

C++ getline() 不需要命名空间声明

c++ - 职能范围是什么意思?

javascript - React 中的多个 url API

powershell - 为什么变量不会更新?

java - Java项目

Javascript 局部变量就像窗口中的类变量一样工作