简体   繁体   中英

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. It will reference the local one variable defined in its parameter list instead.

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. That proves the bom scope lives on within the closure of the b function scope.

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.

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

From closure 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM