在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
所以,我想知道为什么可以访问内部范围内的名称,即使我不在内部范围内?
提前致谢!
最佳答案
没有 var
的变量是在全局上下文中生成的。
Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed.
关于Javascript:为什么我可以访问全局范围内函数内声明的内部名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41723273/