Julio Rodriguez
Julio Rodriguez

Reputation: 515

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.

Upvotes: 0

Views: 55

Answers (2)

mhodges
mhodges

Reputation: 11116

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();

Upvotes: 2

aligumustosun
aligumustosun

Reputation: 152

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

Upvotes: -1

Related Questions