理解javascript函数级范围有困难
我很难理解理解javascript函数级范围有困难,javascript,scope,Javascript,Scope,我很难理解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() {
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();
所以我的问题是
a
是未定义的
,为什么不返回123
?如何
comejs
知道有一个变量“a”将在
这个功能范围,js
是基于解释器的吗k
为什么不是“未定义”第一个代码等于:
var a = 123;
function func() {
var a; //Undefined!
alert(a);
a = 1;
alert(a);
}
这很好地解释了这一点:
代码#1
使所有变量声明位于作用域的顶部,但将赋值保留在原来的位置。当存在对变量的引用时,JavaScript将首先查找当前范围,如果未找到变量,则将继续查找范围链,直到找到变量为止。
此代码的解释如下:
var a = 123; // global var named a declared, assigned a value
function func() {
var a; // the declaration of the local var a gets
// hoisted to the top of the scope, but the
// assignment is left below, so at the point
// it is initialized with a value of `undefined`
alert(a); // looks for a local var named a, finds it but
// it currently has a value of `undefined`
a = 1; // now the value is assigned to the local a
alert(a); // returns 1
}
func();
代码#2
由于以下原因,此代码的行为方式与之相同。
闭包的一个基本定义是JavaScript函数不仅可以访问在其自身范围内定义的变量,还可以访问其父范围内可用的变量
var k = 123; // declares and assigns a value to global k
function func2() {
alert(k); // looks for a local var named k, doesn't find it,
// looks in its parent scope (the global scope in
// this case) finds k, returns its value of 123
var c = 1;
alert(c); //returns 1
}
func2();
这在
js
中称为吊装
,顺便说一句,吊装与功能级别范围不同。例如(在firefox中)尝试同样的方法,使用let
而不是var
。它做同样的事情,let
具有块级作用域,只是想补充一点,这就是所谓的“变量提升”。@Ben感谢您介绍我这个术语,我不知道这个:)