[英]Why the inner function of this Closure I did can not access to the outer function variables?
I was trying to learn about closures and this the following code:我试图了解闭包和以下代码:
var one = 1, two = 2, three = 3; function bom(one, two, three) { console.log(one, two, three); function b(one) { console.log(`From closure ${one}`); }; b(); }; bom(1, 2, 3);
However, the inner function has no access to the outer function variables.但是,内部函数无法访问外部函数变量。
Can anyone explain to me why?谁能向我解释为什么?
Thanks.谢谢。
What @Pointy said is correct, you have done what's called variable shadowing on the one
variable, meaning you have essentially overwritten the reference to the outer one
variable inside the b
function scope. @Pointy 所说的是正确的,您已经对one
变量进行了所谓的变量遮蔽,这意味着您实际上已经覆盖了对b
函数作用域内的外部one
变量的引用。 It will reference the local one
variable defined in its parameter list instead.它将引用在其参数列表中定义的局部变量one
。
That being said, this really isn't an example of a closure, though, as the function definition and calling context are within the same scope.尽管如此,这确实不是一个闭包的例子,因为函数定义和调用上下文在同一范围内。 It would be a better example of closure if you returned the function b
and then executed it later.如果您返回函数b
然后稍后执行它,那将是一个更好的闭包示例。 That proves the bom
scope lives on within the closure of the b
function scope.这证明bom
作用域存在于b
函数作用域的闭包内。
Here's an example:下面是一个例子:
var one = 1, two = 2, three = 3; function bom (one,two, three){ console.log(one,two,three); return function b(){ console.log(`From closure ${one}`); }; }; let myClosureFn = bom(1, 2, 3 ); myClosureFn();
If b and bom got no parameter named one they could use the one that's defined as var.如果 b 和 bom 没有名为 one 的参数,则可以使用定义为 var 的参数。
var one = 1,
two = 2,
three = 3;
function bom (two, three) {
console.log(one, two,three);
function b () {
console.log(`From closure ${one}`);
};
b();
};
bom(2, 3 );
output is :输出是:
1 2 3 1 2 3
From closure 1从关闭 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.