在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
Run Code Online (Sandbox Code Playgroud)
然后,我输入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();
}
Run Code Online (Sandbox Code Playgroud)
这个名字也是如此 fff
> fff // why can I still access the name fff ?
< function (){
console.log("a,b,c is: " + a + "," + b + "," + c);
}
Run Code Online (Sandbox Code Playgroud)
我是一名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;
}
Run Code Online (Sandbox Code Playgroud)
即使在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
Run Code Online (Sandbox Code Playgroud)
所以,我很奇怪为什么即使我不在内部也可以访问内部范围内的名称?
提前致谢!