简体   繁体   中英

variable calling function and calling function directly

I'm learning JavaScript with Manning's book, Get Programming with JavaScript (by John Larsen). In chapter 11, Listing 11.8, the code:

var getCounter = function () {
    var counter = 0;
    var countUpBy1 =  function () {
        counter = counter + 1;
        return counter;
    };  
    return countUpBy1;
};
var count = getCounter();

And I'm using jsbin.com to experiment and learn. In the console:

Q1) why calling count(), the result is not always 1? Why is it, counter is set to 0 at the start, before countUpBy1, shouldn't counter inside countUpBy1 also be 0?

Q2) why calling getCounter() is different from count()? calling count() get me a number (which is what I expect), but calling getCounter() get me:

function () {
    counter = counter + 1;
    return counter;
}

Thanks for explaining in advance.

4/Nov: @DavidFleeman: Am I correct in my understand to first question (I read all 3 links, plus JavaScript Closures 101: What is a closure ?, I never understood JavaScript closures & JavaScript Closures Explained by Mailing a Package :

(deleted my understanding of stepping through the closure)

12/Nov: I never understood JavaScript closures Read this link few more times, and it explained way better than I can.

  1. Why is calling count() not always equal to 1?

These nested methods create a closure where the initialization only happens once, and the nested internal method is returned each time. Please read this link to understand:

https://www.w3schools.com/js/js_function_closures.asp

If you prefer MDN, use below link. However, the above link has example that I believe matches the member's scenario:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

And for even more detail, this seems to be a well thought out explanation:

https://blogs.msdn.microsoft.com/ericlippert/2003/09/17/what-are-closures/

  1. Why does getCounter() return the function object instead of executing the method?

Reading the same link above, you can see how to define getCounter() to do exactly what you are asking it to do. You must define it as a self-invoking function. In your example, it is not defined using the self invoking syntax. See example below if you want to define it to work using getCounter() instead of count().

var getCounter = (function () {
  var counter = 0;
  var countUpBy1 =  function () {
    counter = counter + 1;
    return counter;
  };  
  return countUpBy1;
})();
getCounter();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM