作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我无法理解 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
?如何come js
知道有变量 'a' 将被定义和使用这个函数作用域,js
是基于解释器的吗?
CODE#2 为什么 k
不是“未定义”?
最佳答案
Hoisting导致所有变量声明都被带到范围的顶部,但它将赋值保留在原处。当存在对变量的引用时,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();
由于 closure,此代码的行为方式如此.闭包的一个基本定义是,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();
关于javascript - 难以理解 javascript 函数级范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16002366/
我想模拟这个函数: function getMetaData(key) { var deferred = $q.defer(); var s3 = vm.ini
我是一名优秀的程序员,十分优秀!