在Java的递归函数中使用闭包的计数器示例

问题描述 投票:0回答:1

这是使用反例的Java语言中的闭包说明。

javascript closures counter
1个回答
0
投票

首先,在理解之前,您应该对执行上下文和执行堆栈足够熟悉。参见链接:https://blog.bitsrc.io/understanding-execution-context-and-execution-stack-in-javascript-1c9ea8642dd0。现在,让我们了解什么是闭包。

来自MDN的定义:闭包是捆绑在一起(封闭)的函数和对其周围状态(词汇环境)的引用的组合。

下面的代码段是闭包的示例:

  function callCounter(){
      let x = 0;
    let counter = (x)=>{
          if(x==5){
        console.log("STOP!!");
        }
        else{
        console.log(x);
        counter(++x);
        }
      }
    return counter;
    }
    let y = callCounter();
    y(1);

导致引入Closure的主要步骤是上述代码段中的return counter;。将内部函数的引用传递给外部函数。

示例的执行上下文是:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.