我听不太懂JavaScript
功能级别范围,为C#
程序员看起来有线给我,我会尝试通过代码来解释它:很难理解JavaScript函数级别范围
CODE#1
//Problem
//if same named variable (as in global scope) is used inside function scope,
//then variable defined inside function will be used,global one will be shadowed
var a = 123;
function func() {
alert(a); //returns undefined,why not just return 123 ?
//how come js knew that there is variable 'a' will be defined and used in
//this function scope ,js is interpreter based ?
var a = 1; //a is defined inside function
alert(a); //returns 1
}
func();
CODE#2
//when a variable(inside function) not named as same as the global,
//then it can be used inside function,and global variable is not shadowed
var k = 123;
function func2() {
alert(k); //returns 123 ,why not 'undefined'
var c = 1;
alert(c); //returns 1
}
func2();
所以我的问题是
在CODE#1为什么第一次
a
是undefined
,为什么不它只是返回123
?如何 来js
知道有变量'a'将被定义和使用在 这个功能范围内,js
是基于解释器?in 代码#2为什么不是
k
是'undefined'?
这就是所谓的'hoisting'在'js' http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html – fedosov
BTW hoising是不一样的功能级别范围。尝试例如(在Firefox中)相同,用'let'代替'var'.it做同样的事情,'let'具有块级范围 – user2264587