全局变量在函数中使用时返回undefined

时间:2016-03-11 01:24:32

标签: javascript function variables global-variables

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

document.write(myFunc());

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

输出:未定义

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

document.write(myFunc());

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

输出:1

1 个答案:

答案 0 :(得分: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;