[英]Javascript: why can I access the inner name declared inside a function in global scope?
In chrome developement console, I created a function f with two more embeded function 在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
Then, I input ff
to console, found that I still can access it, while it was defined in the inner scope of f
然后,我在控制台中输入
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();
}
And so does the name fff
fff
这个名字也是如此
> fff // why can I still access the name fff ?
< function (){
console.log("a,b,c is: " + a + "," + b + "," + c);
}
I am a C/C++ developer, and currently toddling in javascript. 我是C / C ++开发人员,目前涉足JavaScript。
This phenomeon seems tricky for me to understand. 对于我来说,这个现象似乎很棘手。
Because in Cpp, it's an error to access the name inside inner scope. 因为在Cpp中,访问内部作用域内的名称是错误的。
for example: 例如:
#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;
}
And even in python, we can't do that too: 即使在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
So, I am wonderring why it is possible to access the name in a inner scope even if I am out of it ? 所以,我想知道为什么即使我不在里面也可以在内部范围内访问该名称 ?
Thanks in advance! 提前致谢!
You haven't used var
to declare ff
or fff
. 您尚未使用
var
声明ff
或fff
。 If you don't declare them, they automatically get declared globally, not locally. 如果不声明它们,它们将自动在全局而不是在本地声明。
So I've not tried it, but this should behave more like what you're after... 所以我没有尝试过,但这应该更像您想要的...
var a = 'ga';
var b = 'gb';
var c = 'gc';
var f = function(){
var a = 'fa';
var b = 'fb';
var ff = function(){
var a = 'ffa';
var fff = function(){
console.log("a,b,c is: " + a + "," + b + "," + c);
};
fff();
};
ff();
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.