嗯,我最近了解了 Javascript 中的闭包。
虽然我发现它的概念确实令人惊叹,但我自己还没有找到适合它们的良好应用程序。
在所有博客文章中,我找到的所有教程中,我都很好地解释了它们是什么以及如何使用它们。
我在任何地方都找不到让我思考的例子:“哇!你可以用闭包做到这一点?太棒了!!!”。我找到的所有例子都像这个一样纯粹是学术性的。
function say667() {
// Local variable that ends up within closure
var num = 666;
var sayAlert = function() { alert(num); }
num++;
return sayAlert;
}
var sayNumber = say667();
alert(sayNumber());
所以,我想知道你们中是否有人可以分享一些关于这些特殊功能的令人兴奋的经历。
我知道这是一个悬而未决的问题,但我会把答案归于最让我惊叹的人。
Thanks
闭包始终与稍后调用的回调函数一起使用,因为它们允许您访问主机调用函数的局部变量,或者可用于将局部变量的值“冻结”到特定回调的私有变量中。随着代码继续执行,但在调用回调之前,局部变量本身将更改为另一个值。
以下是我在此处提供的答案中的关闭示例。
从 setTimeout 回调访问父局部变量:https://stackoverflow.com/a/7032671/816620
将非静态信息传递到延迟回调中:https://stackoverflow.com/a/8660518/816620
我知道上个月我在 SO 答案中使用了数十次闭包(我只是不确定如何通过搜索快速找到更多示例,而无需费力浏览大量帖子)。
而且,这是一个创建私有变量的有用闭包:
function slides(images) {
var slideImages = images || [];
// because of this closure, the variable slideImages is available
// to the method defined in here even though the slides function
// has already finished executing
this.addSlide = function(url) {
slideImages.push(url);
}
this.clearSlides = function() {
slideImages = [];
}
}
// the slideImages variable is not available out here
// it is truly private inside the clsoure
var slideshow = new slides(imgArray);
slideshow.addSlide("xxx.jpeg");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)