JavaScript引擎如何使用冲突的全局变量和局部变量读取和执行函数? [重复]

时间:2022-04-25 16:49:51

This question already has an answer here:

这个问题在这里已有答案:

I need to understand how the JavaScript engines in browsers read functions. Consider the code below:

我需要了解浏览器中的JavaScript引擎如何读取函数。考虑以下代码:

var g = 5;
alert(g); //alerts 5

function haha() {
    alert(g); // alerts NOTHING. Why is this? Why not alert 5? var g = 45 hasn't yet occurred
    var g = 45;
    alert(g); // alerts 45
};

haha();
alert(g); // alerts 5. Because g = 45 is a local variable.

Fiddle

1 个解决方案

#1


5  

The effect you're seeing where alert(g) in the haha function alerts undefined is from variable hoisting.

您看到haha函数警报(g)警报未定义的效果来自变量提升。

The haha function is actually executed as:

哈哈函数实际执行如下:

function haha() {
    var g;
    alert(g);
    g = 45;
    alert(g);
}

This is because variable and function definitions are hoisted to the top of their scope in JavaScript.

这是因为变量和函数定义在JavaScript中被提升到其范围的顶部。

The effect can lead to some rather unintuitive behavior, such as what you're seeing. The simple solution is to always declare your variables and functions before any executing code so that the written code matches what's being executed.

这种效果可能导致一些相当不直观的行为,例如你所看到的。简单的解决方案是在任何执行代码之前始终声明您的变量和函数,以便编写的代码与正在执行的代码匹配。

#1


5  

The effect you're seeing where alert(g) in the haha function alerts undefined is from variable hoisting.

您看到haha函数警报(g)警报未定义的效果来自变量提升。

The haha function is actually executed as:

哈哈函数实际执行如下:

function haha() {
    var g;
    alert(g);
    g = 45;
    alert(g);
}

This is because variable and function definitions are hoisted to the top of their scope in JavaScript.

这是因为变量和函数定义在JavaScript中被提升到其范围的顶部。

The effect can lead to some rather unintuitive behavior, such as what you're seeing. The simple solution is to always declare your variables and functions before any executing code so that the written code matches what's being executed.

这种效果可能导致一些相当不直观的行为,例如你所看到的。简单的解决方案是在任何执行代码之前始终声明您的变量和函数,以便编写的代码与正在执行的代码匹配。