1

I am trying to get a better fundamental understandings of JavaScript's closure

say we have these two different scenarios in Node.js

function A(){

 console.log(data);  //this should give us a null pointer

}


module.exports = function(data){

    return A;

}

versus

module.exports = function(data){

   return function A(){

     console.log(data); // variable "data" will be remembered

   };

}

why is it that in the first case the variable "data" is not remembered but in the latter case it is "remembered" by the closure?

I am sure in some language somewhere, declaring a function and referencing a function might both remember the variables in the outer function, but I guess I want to better understand the difference.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 1
    There is a great community wiki on this at [How do JavaScript closures work](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1) – PSWai Dec 29 '15 at 04:24

3 Answers3

4

Closures are about lexical inclusion. The word "lexical" in this context refers to the textual structure of the program, and "lexical inclusion" means that one construct is physically found "inside", or nested within, another. In JavaScript, functions have access to variables which are defined in lexically surrounding (enclosing) structures.

Therefore, in the following:

function foo() {
  var bar;
  return function baz() {
    console.log(bar);
  };
}

The function baz is lexically included within foo, which defines the variable bar, and therefore has access to bar. It continues to have access to bar even when it is returned and invoked from elsewhere:

var fooFunc = foo();
fooFunc();            // continues to have access to bar

In your example:

function A(){
  console.log(data);  //this should give us a null pointer
}

module.exports = function(data) {
  return A;
}

A does not have access to data, since it is not lexically included within the context of the function defined on the module.exports line, which is where data is defined (or in this case, passed in).

0

you are using closure for variable data in the second case , that's why it gives you the correct result.

In the first case you are just return the function A, not closing over data variable in exports.

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
0

Because in your first example, the two data are not related and are independent of each other.

mariocatch
  • 8,305
  • 8
  • 50
  • 71