JavaScript 局部和全局变量混淆

我是 JavaScript 的新手,我在局部和全局变量作用域上做了一些实践。以下是我的代码(小提琴) :

var myname = "initial"
function c(){
alert(myname);
var myname = "changed";
alert(myname);
}
c();

当调用第一个警报时,它将 myname显示为未定义的。所以我的困惑是为什么我不能访问 myname的全局实例,如果我没有在函数中定义 myname,那么它将工作得很好。

21718 次浏览

It is not replacing the global variable. What is happening is called "variable hoisting". That is, var myname; gets inserted at the top of the function. Always initialize your variables before you use them.

Try this:

var myname = "initial";


function c() {
alert(myname);
myname = "changed";
alert(myname);
}


c();

In JavaScript, the variable declarations are automatically moved to the top of the function. So, the interpreter would make it look more like this:

var myname = "initial"
function c(){
var myname;
// Alerts undefined
alert(myname);
myname = "changed";
// Alerts changed
alert(myname);
}
c();

This is called hoisting.

Due to hoisting and the fact that the scope for any variable is the function it's declared in, it's standard practice to list all variables at the top of a function to avoid this confusion.