混淆加法运算符逻辑

时间:2017-11-16 15:33:16

标签: javascript function

为什么变量计数器在自调用函数中重新初始化为0时会继续增加?

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

 add();
 add();
 add();

 // the counter is still 3 when this line of code exists
 // var counter = 0;

因此,当调用add()函数时,函数首先运行,初始化counter = 0并返回另一个函数,该函数返回计数器的增量值。为什么会出现 var counter = 0;

的情况

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

编辑:2017年11月16日

好的,现在从这个页面上给出的两个答案中得到更多的理解。为了进一步澄清,我将添加自己的推理,以便更好地了解这种情况发生的原因。

 //first call of add()
 (function(){ // a self-invoking function
    var counter = 0; // executes once with the self-invoking function
    return function() { return counter += 1; } //explained below
 });

 //since the self-invoke function ran already, add() will begin to run the returned function:
 add = function() { return counter += 1; };
 add(); ----> counter += 1; -----> add.counter = 1;
 //counter acts like this.counter, so it's a part of add()
 //counter is now at 1

 //second call of add();
 //add has now officially been **transformed** to the new function:
 add = function() {
    return counter += 1;
 };
 //while add.counter still **exists** and remains in the self-invoke 
 //function. Do we call this **limbo variable** ? Don't know.
 //add.counter is at 2

 //third call of add();
 function() {
   return counter += 1;
 }
 //add.counter is at 3!

2 个答案:

答案 0 :(得分:3)

请注意" var add"分配了一个自动调用函数,它返回一个函数。 无论返回语句如何,自调用函数闭包。这意味着它可用于返回的函数。 所以它实际上只是初始化一次。然后是return函数,这是变量"添加" now contains,在调用它时递增计数器。

答案 1 :(得分:2)

因为变量add包含自调用函数的结果。所以add的价值是这样的:

function () {
    return counter += 1;
}

计数器变量仅在此函数设置为add变量之前初始化。

相关问题