简体   繁体   English

使用闭包在 function 内部进行计数

[英]Using closure for counting inside a function

I tried this and it always show 1 time, something's wrong, how to fix this?我试过了,它总是显示1次,出了点问题,如何解决这个问题?

    function myFunc() {

        var increment = (function() {
          var i = 0;
        
          return function() {
            i++;
            return i;
          };
        })();
        
        alert(`calling myFunc ${increment()} times`);

    }

Any time you call my func it's going to redefine the increment function, so you shouldn't expect it to ever say anything other than 1 .任何时候你调用我的函数,它都会重新定义增量 function,所以你不应该期望它会说除1之外的任何内容。 Your problem is that increment is being defined on every call to myFunc您的问题是每次调用myFunc时都会定义增量

What you want to do is this:你想要做的是:

var i = 0;
function myFunc() {
    var increment = (function() {
        return function() {
            i++;
            return i;
        };
    })();
        
    alert(`calling myFunc ${increment()} times`);
}

So now i will keep its values between calls to myFunc .所以现在i将在调用myFunc之间保留它的值。 It'll have to be outside myFunc .它必须在myFunc之外。 Or you can move the whole function outside of myFunc .或者您可以将整个 function 移到myFunc之外。

var increment = (function() {
    var i = 0;
        
    return function() {
        i++;
        return i;
    };
})();
function myFunc() {
    alert(`calling myFunc ${increment()} times`);
}

Now this works:现在这有效:

console.log(increment()); // logs 1
console.log(increment()); // logs 2

The issue is that when a variable goes out of scope it is destroyed, the next time a value is called it will be recreated, and initialized at whatever value it starts as.问题是,当一个变量超出 scope 时,它会被销毁,下次调用一个值时,它将被重新创建,并以它开始的任何值初始化。 As the variable i is scoped to inside the increment function, which is itself scoped to myFunc it means that when myFunc that closure is destroyed and will be created the next time the function is run.由于变量i被限定在increment function 内,而增量 function 本身的作用域是myFunc ,这意味着当myFunc关闭时,该闭包将在下一次运行 function 时创建。

An example that shows i hoisted to be in myFunc 's scope and the increment function running several times.一个例子显示i被提升到myFunc的 scope 和increment function 运行多次。

 function myFunc() { console.log('running myFunc'); var i = 0; console.log('assigning i to ' + i); function increment() { console.log('incrementing'); i++; }; increment(); increment(); console.log(`calling myFunc ${i} times`); } myFunc();

Notice that i now maintains its state across calls to increment .请注意, i现在在对increment的调用中维护其 state 。 Now when we call myFunc multiple times, we see that i is destroyed, then a new variable is created when myFunc is run again.现在当我们多次调用myFunc时,我们看到i被销毁,然后当myFunc再次运行时会创建一个新变量。

 function myFunc() { console.log('running myFunc'); var i = 0; console.log('assigning i to ' + i); function increment() { console.log('incrementing'); i++; } increment(); increment(); console.log(`calling myFunc ${i} times`); } myFunc(); myFunc();

Now if we hoist i up to be above the scope of myFunc we'll see that it's value is kept within scope across calls to myFunc .现在,如果我们将i提升到myFunc的 scope 之上,我们将看到它的值在对myFunc的调用中保持在 scope 内。

 var i = 0; console.log('assigning i to ' + i); function myFunc() { console.log('running myFunc'); function increment() { console.log('incrementing'); i++; } increment(); console.log(`calling myFunc ${i} times`); } myFunc(); myFunc();

Works for me.为我工作。

 var increment = (function() { var i = 0; return function() { i++; return i; }; })(); console.log(increment()); console.log(increment()); console.log(increment());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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