3

I have a problem with understanding closure when I have 3 level of scopes

https://jsfiddle.net/Ar2zee/wLy8rkyL/1/

How I can get access to parameter "g" in level3 function,

var a = 10;

function level1(b) {
  var c = 1;

  function level2(f) {
    var d = 2;

    function level3(g) {
      return a + b + c + d + f + g;
    }
    return level3()
  }
  return level2;
}
var temp = level1(10);
var temp2 = temp(10);
var temp3 = temp2(10);
console.log(temp3(10)); // or level(10)();  without variable

Thank you !

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Ar2zee
  • 410
  • 1
  • 4
  • 12

2 Answers2

1

Line:1 invokes level1 fn and get back fn level2 stored in alias temp.
Line:2 invokes temp fn and get back fn level3 stored in alias temp2.
Line:3 now when invoking temp2 fn you execute fn level3 getting back the result of addition operation.

So temp3 is not a function but a value.

var a = 10;

function level1(b) {
  var c = 1;

  function level2(f) {
    var d = 2;

    function level3(g) {
      return a + b + c + d + f + g;
    }
    return level3;
  }
  return level2;
}
var temp = level1(10);
var temp2 = temp(10);
var temp3 = temp2(10);
console.log(temp3); // or level(10)();  without variable
MaxZoom
  • 7,619
  • 5
  • 28
  • 44
  • Thank you so much . inside functions never use returns with parentheses just name of the functions and thats it or I can use parentheses in some cases ? – Ar2zee Jun 07 '17 at 15:45
  • It really depends what you want to achieve, if you want a function then do not call it and if you want result, then call it (with parenthesis). – MaxZoom Jun 07 '17 at 15:54
0

Just replace

Return level3()

With

Return level3
Jagga
  • 189
  • 2
  • 9
  • what a reason to passed number inside a function if I wanna make it dynamically and change it in future for example ??? – Ar2zee Jun 07 '17 at 15:48