这个JavaScript代码片段令人困惑 [英] Puzzled by this JavaScript code snippet
问题描述
对于这个片段,我并不感到惊讶全局变量'a'的评估结果是5。
For this snippet, I'm not surprised global variable 'a' evaluates to be 5.
http://jsfiddle.net/MeiJsVa23/gZSxY/ :
var a = 10;
function func(){
a = 5;
}
func(); // expect global variable 'a' to be modified to 5;
alert(a); // and this prints out 5 as expected. No surprise here.
但是为什么这个代码片段,全局变量'a'评估为10而不是5?好像 a = 5
从未发生过。
But how come for this code snippet, global variable 'a' evaluates to be 10 and not 5? It's as if the a = 5
never happened.
http://jsfiddle.net/MeiJsVa23/2WZ7w/ :
var a = 10;
function func(){
a = 5;
var a = 23;
}
func(); // expect global variable 'a' to be modified to 5;
alert(a); // but this prints out 10!! why?
推荐答案
这是由于变量提升:用 var
关键字定义的任何内容都被提升到当前范围的顶部,创建一个局部变量 A
。请参阅: http://www.adequatelygood.com/2010/2/JavaScript -Scoping-and-Hanging
This is due to variable hoisting: anything defined with the var
keyword gets 'hoisted' to the top of the current scope, creating a local variable a
. See: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
这篇关于这个JavaScript代码片段令人困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!