最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

I decided to make one step forward on trying to understand Javascript and read again Javascript: The Good Parts. And here es 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...)

I decided to make one step forward on trying to understand Javascript and read again Javascript: The Good Parts. And here es 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...)

Share Improve this question edited Aug 9, 2012 at 6:41 user166390 asked Aug 9, 2012 at 6:00 NobitaNobita 23.7k11 gold badges63 silver badges87 bronze badges 5
  • Does Crockford actually suggest this? What page? This would make a lot more sense if there were a final () at the end of your code, meaning that digit_name gets the return value of the outer function, which is the inner function. – apsillers Commented Aug 9, 2012 at 6:04
  • My mistake. Forgot to add (); at the end. Sorry guys. – Nobita Commented Aug 9, 2012 at 6:04
  • "I want to avoid using the global variables because they are evil," - No they're not, any more than, say, knives are evil - it's how you use them that matters. (And even then, inappropriate use of globals is...inappropriate - not evil.). But in any case the code you start with to avoid globals immediately creates a global (digit_name). – nnnnnn Commented Aug 9, 2012 at 6:33
  • @nnnnnn: I was actually citing D.Crockford, I have heard him saying that in two conferences :) – Nobita Commented Aug 9, 2012 at 6:34
  • 2 Yes, Mr Crockford seems to see everything in absolutes. I think grey areas make him nervous. (Not to say that he doesn't have plenty of good advice - the problem is figuring out which bits of advice are just his personal preferences presented as "facts".) – nnnnnn Commented Aug 9, 2012 at 6:42
Add a ment  | 

3 Answers 3

Reset to default 12

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 bees:

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 remend taking a look at a visual explanation of closures, like this one: http://www.bennadel./blog/1482-A-Graphical-Explanation-Of-Javascript-Closures-In-A-jQuery-Context.htm

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.

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.

发布评论

评论列表(0)

  1. 暂无评论