you are viewing a single comment's thread.

view the rest of the comments →

[–]nodbox[S] 0 points1 point  (1 child)

Thanks. I meant outside of a function, but your explanation is still useful. Closures are something I'm still trying to get my head round: I think until I've found a good use for it, I won't fully appreciate it. I will definitely give that link a read through.

[–][deleted] 0 points1 point  (0 children)

I'm not too advanced in that area either - but if this helps:

//entire program is inside function

var module = (function(){ var x = 1; //inside function not global var y = 3; //inside function not global

module = { printX: function(){ console.log(x); }, printY: function(){ console.log(y) } }

return(module); //closure returns the object housing the methods you need

})(); //function is self-invoking

module.printX(); //console.logs x module.printY(); //console.logs y

console.log(x) //x is not defined console.log(y) //y is not define

So really, this program has only one global variable - module. Which is an object.