在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中,访问内部范围内的名称是错误的.
例如:
#includeusing 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
所以,我很奇怪为什么即使我不在内部也可以访问内部范围内的名称?
提前致谢!
var
在全局上下文中生成没有变量的变量.
在执行赋值时,为未声明的变量赋值会隐式地将其创建为全局变量(它将成为全局对象的属性).