Javascript本地和全局变量混淆 [英] Javascript local and global variable confusion
问题描述
我是JavaScript的新手,我在本地和全局变量范围上做了一些练习,以下是我的代码(小提琴):
I am new to JavaScript and I was doing some practices on local and global variable scopes, following is my code(fiddle):
var myname = "initial"
function c(){
alert(myname);
var myname = "changed";
alert(myname);
}
c();
当第一个调用alert,它显示 myname
为undefined。所以我的困惑是为什么我无法访问 myname
的全局实例,如果我没有定义 myname
在函数中,它将正常工作。
when the first alert is called, it is showing myname
as undefined. so my confusion is why I am not able to access a global instance of myname
and if I don't define myname
within the function then it will work fine.
推荐答案
在Javascript中,变量声明会自动移动到函数的顶部。因此,解释器会使它看起来更像这样:
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();
这称为'吊装'。
由于吊装以及任何变量的范围是其声明的函数这一事实,标准做法是列出所有变量函数的顶部以避免这种混淆。
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.
这篇关于Javascript本地和全局变量混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!