【发布时间】:2017-01-18 15:30:18
【问题描述】:
在 chrome 开发控制台中, 我创建了一个函数 f 和另外两个嵌入函数
> var a = 'ga';
var b = 'gb';
var c = 'gc';
var f = function(){
var a = 'fa';
var b = 'fb';
ff = function(){
var a = 'ffa';
fff = function(){
console.log("a,b,c is: " + a + "," + b + "," + c);
};
fff();
};
ff();
};
< undefined
然后,我在控制台输入ff,发现还是可以访问的,
而它是在f的内部范围内定义的
> ff // why can I still access the name ff ?
< function (){
var a = 'ffa';
fff = function(){
console.log("a,b,c is: " + a + "," + b + "," + c);
};
fff();
}
fff这个名字也是如此
> fff // why can I still access the name fff ?
< function (){
console.log("a,b,c is: " + a + "," + b + "," + c);
}
我是一名 C/C++ 开发人员,目前正在学习 javascript。
这种现象对我来说似乎很难理解。
因为在 Cpp 中,访问内部范围内的名称是错误的。
例如:
#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
auto f = [](){
std::cout << "in f() now" << std::endl;
auto ff = [](){
std::cout << "in ff() now" << std::endl;
auto fff = [](){
std::cout << "in fff() now" << std::endl;
};
fff();
};
ff();
};
f(); //it's okay
ff(); // not okay, error: use of undeclared identifier 'ff'
fff(); // not okay too, error: use of undeclared identifier 'fff'
return 0;
}
即使在 python 中,我们也不能这样做:
def f():
print("in f() now")
def ff():
print("in ff() now")
def fff():
print("in fff() now")
fff()
ff()
f() # okay
ff() # NameError: name 'ff' is not defined
fff() # NameError: name 'fff' is not defined
所以,我想知道为什么即使我不在其范围内,也可以在内部范围内访问名称?
提前致谢!
【问题讨论】:
-
因为 JS 就是这样设计的。如果没有使用
var/const/let的声明,它将分配给全局变量。
标签: javascript scope closures