全局变量在函数中使用时返回未定义

global variable returns undefined when used in a function

本文关键字:返回 未定义 函数 全局变量      更新时间:2023-09-26

当我在func之外定义变量时,它返回undefined。我找不到原因。

document.write(myFunc());
var x = 1;
function myFunc() {
    return x;
}

输出:未定义

但是,如果我在函数中定义变量,它可以工作。

document.write(myFunc());
function myFunc() {
    var x = 1;
    return x;
}

输出: 1

你犯了一个常见的误解。变量和函数声明在执行任何代码之前进行处理,但赋值在代码中按顺序发生。因此,您的代码实际上是:

// Function declarations are processed first
function myFunc() {
    return x;
}
// Variable declarations are processed next and initialised to undefined
// if not previously declared
var x;
// Code is executed in sequence
document.write(myFunc());
// Assignment happens here (after calling myFunc)
x = 1;