繁体   English   中英

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

[英]global variable returns undefined when used in a function

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

document.write(myFunc());

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

输出:未定义

但是,如果我在func内部定义变量,则它可以工作。

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;

暂无
暂无

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

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