gpt4 book ai didi

javascript - JavaScript 中的递归闭包

转载 作者:数据小太阳 更新时间:2023-10-29 05:31:56 26 4
gpt4 key购买 nike

enter image description here

function buildList( list ) {
var i = 0;
var first = function () {
console.log( "in" )
console.log( i );
}
var Second = function () {
console.log( "out" )
first();
}
return Second;
}

var a = buildList( [1, 2, 3] )
console.dir( a );

a(); // Here closure is created which has function first ,Here first also has one closure of itself that means recursive closure

当我在 Chrome 中看到我的控制台时,它有一个首先具有函数的闭包,它也有一个自身的闭包,即它在闭包中有其自身函数的重复循环,有谁知道这里发生了什么,我很困惑,为什么会有无限闭环

最佳答案

闭包是一种特殊的对象,它结合了两件事:一个函数,以及创建该函数的环境。

  1. 无需混淆,此代码的行为与预期的相同。这里发生的事情是,当您在代码中执行 console.dir( a ); 时,它会返回 Second 函数,我认为您很清楚。

  2. 现在,当您展开此函数时,它会在Closure 中显示Second 的父函数(环境函数),这是 buildList。在您的代码中,它正在做同样的事情。

  3. 现在下一步是扩展这个函数 buildList,它会显示给你的是它的子对象,它们是var i = 0;函数优先。您的控制台按预期显示。

  4. 现在,当您再次打开 first() 时,它会在 Closure 中显示 的父函数(环境函数) code>first,即buildList。 (与第 2 步相同)。

现在它再次重复第 3 步,然后重复第 4 步。依此类推...也许你明白这里发生了什么。

关于javascript - JavaScript 中的递归闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41297307/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com