gpt4 book ai didi

javascript - 对 JavaScript 中的闭包感到困惑

转载 作者:行者123 更新时间:2023-12-02 07:41:37 25 4
gpt4 key购买 nike

Possible Duplicate:
How do JavaScript closures work?
Javascript closures and side effects in plain English? (separately)

我是 JavaScript 新手,但我对闭包的工作原理感到非常困惑。有人可以通俗地解释一下它们是什么或者为什么它们有用吗?

最佳答案

闭包类似于函数定义时的上下文。每当定义函数时,都会存储上下文,即使函数的“正常”生命周期结束,如果您保留对函数执行中定义的元素的引用,它仍然可以访问上下文的元素(闭包),这实际上是函数定义中的范围。抱歉我的英语不好,但这个例子可能会让你理解:

function test() {
var a = "hello world";
var checkValue = function() { alert(a); };
checkValue();
a = "hi again";
return checkValue;
}

var pointerToCheckValue = test(); //it will print "hello world" and a closure will be created with the context where the checkValue function was defined.
pointerToCheckValue(); //it will execute the function checkValue with the context (closure) used when it was defined, so it still has access to the "a" variable

希望有帮助:-)

关于javascript - 对 JavaScript 中的闭包感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8171959/

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