Nobita
Nobita

Reputation: 23713

How does this JavaScript closure-function reuse an object without a global variable?

I decided to make one step forward on trying to understand Javascript and read again Javascript: The Good Parts. And here comes the first doubt:

Let's say I want to avoid using the global variables because they are evil, and so I have the following:

var digit_name = function(n) {
 var names = ['zero','one','two','three'];
 return names[n];
}

D.Crockford claims that this is slow because everytime the function gets called, a new instantiation of names is done. So, then he moves to the closure solution by doing this:

var digit_name = function () {
  var names = ['zero', 'one', 'two', 'three'];
  return function (n) {
    return names[n];
  }
}();

This makes the names variable stored in memory and therefore it doesn't get instantiated every time we call digit_name.

I want to know why? When we call digit_name, why is the first line being "ignored"? What am I missing? What is really happening here?

I have based this example not just in the book, but on this video (minute 26)

(if someone thinks of a better title, please suggest as appropriate...)

Upvotes: 12

Views: 1841

Answers (3)

slebetman
slebetman

Reputation: 113906

This is not an answer but a clarification in case the given examples still seem confusing.

First, lets clarify. digit_name is not the first function you see in the code. That function is just created to return another function (yes, you can return functions just like you can return numbers or strings or objects, in fact functions are objects):

var digit_name = (
    function () { // <------------------- digit name is not this function

        var names = ['zero', 'one', 'two', 'three'];

        return function (n) { // <------- digit name is really this function
            return names[n];
        }
    }
)();

To simplify the example and illustrate just the idea of closures rather than mix it up with things like self calling functions (which you might not be familiar with yet) you can re-write the code like this:

function digit_name_maker () {
    var names = ['zero', 'one', 'two', 'three'];

    return function (n) {
        return names[n];
    }
}

var digit_name = digit_name_maker(); // digit_name is now a function

What you should note is how even though the names array is defined in the digit_name_maker function it is still available in the digit_name function. Basically both functions share this array. That basically is what closures are: variables shared between functions. I like to think of it as a kind of private global variable - it feels like globals in that all the functions have shared access to it but code outside of the closure can't see it.

Upvotes: 3

Elliot B.
Elliot B.

Reputation: 17661

I'm sure you meant to make your second example function an immediate executing (i.e., self-invoking) function, like this:

var digit_name = (function () {
  var names = ['zero', 'one', 'two', 'three'];
  return function (n) {
    return names[n];
  }
})();

The distinction involves scope chain with closures. Functions in JavaScript have scope in that they will look up into parent functions for variables that are not declared within the function itself.

When you declare a function inside of a function in JavaScript, that creates a closure. A closure delineates a level of scope.

In the second example, digit_name is set equal to a self-invoked function. That self-invoked function declares the names array and returns an anonymous function.

digit_name thus becomes:

function (n) {
  //'names' is available inside this function because 'names' is 
  //declared outside of this function, one level up the scope chain
  return names[n];
}

From your original example, you can see that names is declared one up level up the scope chain from the returned anonymous function (which is now digit_name). When that anonymous function needs names, it travels up the scope chain until it finds the variable declared--in this case, names is found one level up the scope chain.

Regarding efficiency:

The second example is more efficient because names is only declared once--when the self-invoking function fires (i.e., var digit_name = (function() { ... })(); ). When digit_names is called, it will look up the scope chain until it finds names.

In your first example, names gets declared every time digit_names is called, so it is less efficient.

Graphical example:

The example you've provided from Douglas Crockford is a pretty tough example to start out with when learning how closures and scope chains work--a lot of stuff packed into a tiny amount of code. I'd recommend taking a look at a visual explanation of closures, like this one: http://www.bennadel.com/blog/1482-A-Graphical-Explanation-Of-Javascript-Closures-In-A-jQuery-Context.htm

Upvotes: 12

Joseph
Joseph

Reputation: 119847

Simply put, the issue with the first code is that it creates an array upon each call and returns a value from it. It's an overhead due to the fact that you are creating an array everytime you call.

In the second code, it creates a closure that declares only a single array and returns a function that returns a value from that array. Basically, digit_name now carries it's own array instead of making one every call. Your function gets from an existing array from the closure.


On the other hand, closures, if not used properly can and will eat up memory. Closures are usually used to protect inner code from the outer scopes, and usually, implemented with limited access from the outside.

Objects don't get destroyed by the GC unless all references to them are "nulled". In the case of closures, if you can't get in them to kill those inner references, then the objects will not be destroyed by the GC and forever will eat memory.

Upvotes: 0

Related Questions