我很难理解JavaScript
函数级别的范围,作为一个C#
程序员,它看起来与我有关,我将尝试通过代码来解释它:
代码#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();
代码#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
是基于解释器的吗?在CODE#2为什么不是
k
“未定义”?