0

I have following code snippet to be executed,

function OuterFn(){
        var slices = 0; // variable inside Outer function
        this.getSlices = function(){
            return slices;
        }
        this.slice = function(){
            slices++;
        }
    }
    var outerFn = new OuterFn();
    console.log(outerFn.getSlices());
    console.log(outerFn.slices); // print outer function variable

Why output of this code is:
0
undefined

13
  • 3
    It's called closures. You cannot access the inner variable unless you return it or assign it to a global one. This is the main concept of it. Private variables. Commented Oct 10, 2016 at 5:25
  • I am confused about your comment "print outer function", what is that ? Commented Oct 10, 2016 at 5:30
  • Slices is a variable defined inside the function's scope. It only exists in the function's closure (I recommend you [github.com/getify/You-Dont-Know-JS/tree/master/… to better understand it). OuterFn()'s this object, in your example, references to the newly created object outerFn (or whatever other new objects you create using new OuterFn()). For more about this, see [github.com/getify/You-Dont-Know-JS/tree/master/… Commented Oct 10, 2016 at 5:42
  • @Rayon my mistake. Edited. Commented Oct 10, 2016 at 5:44
  • @Rayon Both links are 404 :( Commented Oct 10, 2016 at 5:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.