gpt4 book ai didi

javascript - 创建闭包的条件是什么?

转载 作者:行者123 更新时间:2023-12-03 05:11:21 25 4
gpt4 key购买 nike

在我天真的概念中,闭包只是另一个函数返回的函数,它在返回后保留外部函数的范围:

var factory = function(y){
var x = 2;
return function(){
console.log(x+y);
}
}

var closure1 = factory(2);
closure1(); // output 4

var closure2 = factory(10);
closure1(); // output 4
closure2(); // output 12

虽然我不明白为什么在循环中添加事件处理程序会创建闭包? (如 MDN 所示)事件处理程序没有显式返回,这不是本问题的关注点。

<小时/>

然后我又遇到了另一个page ,在代码片段#2:附近,它说

The onclick function would create a closure if it referenced variables in its scope, but it doesn’t.

这是否意味着在循环中

nodes[i].onclick = function () { return false; }; 不是闭包

但是如果我把它改成

nodes[i].onclick = function () { console.log(i);返回假; };

然后就结束了?

<小时/>

结合上面的部分,我创建闭包的概念是

  1. 它必须是另一个函数中返回的函数,或者附加在另一个函数中的回调函数
  2. 内部函数必须以某种方式访问​​外部函数的作用域

当满足 1 和 2 时是否会创建闭包?

最佳答案

a closure is simply a function return by another function, which preserve the scope of the outer function after it returns

关闭。

这是一个在其内部创建的函数完成后仍然有指向它的引用的函数。

返回它是保留对其引用的一种方法。

Though I do not understand why adding event handler in loop will create closures?

该引用被传递给事件处理代码。这会在传递它的函数完成后保留它。

<小时/>

Does that mean that in the loop …

是的,确实如此。

<小时/>

It needs to be a function returned in another function, or the callback function which attached in another function

没有。只要保留引用,引用就可以去任何地方。

var obj = {};

function create() {

var foo = 1;

obj.bar = function() {
console.log(foo++);
};
}

create();

obj.bar();
obj.bar();
obj.bar();
obj.bar();

The inner function MUST somehow access outer function's scope

是的

关于javascript - 创建闭包的条件是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41804339/

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