我无法理解JavaScript功能级别的范围,作为一个C#程序员,它看起来与我联系,我将尝试通过代码解释它:
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();
Run Code Online (Sandbox Code Playgroud)
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();
Run Code Online (Sandbox Code Playgroud)
所以我的问题是
在CODE#1,为什么第一次a是undefined,为什么不它只是回归123?怎么js知道在这个函数范围内有变量'a'将被定义和使用,js是基于解释器吗?
在CODE#2中为什么不是k'undefined'?
提升会导致所有变量声明都被置于范围的顶部,但它会将赋值保留在原来的位置.当存在对变量的引用时,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();
Run Code Online (Sandbox Code Playgroud)
此代码的行为方式与闭包有关.闭包的基本定义是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();
Run Code Online (Sandbox Code Playgroud)
第一个代码与此相同:
var a = 123;
function func() {
var a; //Undefined!
alert(a);
a = 1;
alert(a);
}
Run Code Online (Sandbox Code Playgroud)
这很好地解释了它:https: //developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/var
| 归档时间: |
|
| 查看次数: |
2083 次 |
| 最近记录: |