Javascript 局部变量和全局变量混淆
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19721313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript local and global variable confusion
提问by Bharat Soni
I am new to JavaScript and I was doing some practices on local and global variable scopes, following is my code(fiddle):
我是 JavaScript 的新手,我正在对本地和全局变量范围做一些练习,以下是我的代码(小提琴):
var myname = "initial"
function c(){
alert(myname);
var myname = "changed";
alert(myname);
}
c();
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.
当第一个警报被调用时,它显示myname
为未定义。所以我的困惑是为什么我无法访问的全局实例,myname
如果我不在myname
函数中定义,那么它会正常工作。
采纳答案by EmptyArsenal
In Javascript, the variable declarations are automatically moved to the top of the function. So, the interpreter would make it look more like this:
在 Javascript 中,变量声明会自动移动到函数的顶部。所以,解释器会让它看起来更像这样:
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.
由于提升以及任何变量的作用域都是它在其中声明的函数这一事实,标准做法是在函数顶部列出所有变量以避免这种混淆。
回答by Sridhar R
It is not replace 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;
被插入到函数的顶部。在使用变量之前始终初始化它们 - 试试这个:
var myname = "initial";
function c() {
alert(myname);
myname = "changed";
alert(myname);
}
c();