对JavaScript中的闭包感到困惑
可能重复:对JavaScript中的闭包感到困惑,javascript,closures,Javascript,Closures,可能重复: 我是JavaScript新手,但我对闭包的工作方式感到困惑。有人能用外行的语言解释一下它们是什么或者为什么它们有用吗?我强烈推荐以下内容。我发现这是理解闭包的一个很好的起点。如果你从一个简单的用法开始,我从 发生的情况是变量num被捕获(封闭)在addNum函数中 如果您有这样的东西(预计不会正常运行),这将变得很方便: for(var t = 0; t < 5; t++) { var elem = document.getElementById('mydiv' + t
我是JavaScript新手,但我对闭包的工作方式感到困惑。有人能用外行的语言解释一下它们是什么或者为什么它们有用吗?我强烈推荐以下内容。我发现这是理解闭包的一个很好的起点。如果你从一个简单的用法开始,我从 发生的情况是变量
num
被捕获(封闭)在addNum
函数中
如果您有这样的东西(预计不会正常运行),这将变得很方便:
for(var t = 0; t < 5; t++) {
var elem = document.getElementById('mydiv' + t);
elem.onclick = function(e) {
alert(t);
};
};
for(var t=0;t<5;t++){
var elem=document.getElementById('mydiv'+t);
elem.onclick=函数(e){
警报(t);
};
};
这应该显示使用此事件处理程序设置的每个div的值5
如果将计数器实例包含在事件处理程序中,则每个计数器的实例都可能不同,这是预期的行为
这是一个相当高级的话题。一旦你对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
希望有帮助:-)请看,您可以在这里找到有关闭包的好信息-
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