2

I was reading about AngularJS and came across the following statement on a newsgroup:

I have to say, though, that the more I use Angular, the less interest I have in creating classes. Classes are not where javascript is at! You can do pretty much everything you need with pure functions and closures and then you don't have to worry about the troublesome "this" and "that".

Can someone explain what is meant by "closures".

mishmash
  • 4,422
  • 3
  • 34
  • 56
  • Which are you asking... your title, or your last sentence? Functional approaches have their place, and prototypal inheritance has its place. It would be unfortunate to exclude either one. The "this" and "that" issue isn't a big deal. –  Apr 19 '13 at 07:04
  • Since javascript doesn't have classes (it has prototypes/objects), your question doesn't make a whole lot of sense. – jfriend00 Apr 19 '13 at 07:47

1 Answers1

1

Closures are a structure in Javascript code where within nested functions the outer functions scope is retained within the inner function.

For Example:

function outer(x,y){
    var t = 1;
    return function(z){
        //x, y, t from the outer function are made available to inner function
        return x + y + z + t; 
    }
}

var outer1 = outer(1,1);  //creating a closure, or an instance of a function in sense
alert(outer1(1)); //Alerts 4

var outer2 = outer(2,2);
alert(outer2(2)); //Alerts 7

The simple explanation of a Closure is that ECMAScript allows inner functions; function definitions and function expressions that are inside the function bodes of other functions. And that those inner functions are allowed access to all of the local variables, parameters and declared inner functions within their outer function(s). A closure is formed when one of those inner functions is made accessible outside of the function in which it was contained, so that it may be executed after the outer function has returned. At which point it still has access to the local variables, parameters and inner function declarations of its outer function. Those local variables, parameter and function declarations (initially) have the values that they had when the outer function returned and may be interacted with by the inner function.

Source

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189