此解决方案使用闭包和递归。
var SlideChanger = function(seconds_each) {
var index = -1;
// on the first cycle, index will be set to zero below
var maxindex = ($(".change_link").length) - 1;
// how many total slides are there (count the slide buttons)
var timer = function() {
// this is the function returned by SlideChanger
var logic = function() {
// this is an inner function which uses the
// enclosed values (index and maxindex) to cycle through the slides
if (index == maxindex)
index = 0; // reset to first slide
else
index++; // goto next slide, set index to zero on first cycle
$('.slideshow').blinds_change(index); // this is what changes the slide
setTimeout(logic, 1000 * seconds_each);
// schedule ourself to run in the future
}
logic(); // get the ball rolling
}
return timer; // give caller the function
}
SlideChanger(5)(); // get the function at five seconds per slide and run it
我们在这里所做的是将内部函数timer 暴露在定义它的函数之外(SlideChanger)。这个函数 (timer) 可以访问在 SlideChanger (index 和 maxindex) 中定义的变量。
现在我们已经设置了封闭环境中的变量和返回调用者的函数,我们可以在logic 中设置逻辑引擎。当logic 运行时,它使用index 和maxindex 来确定接下来应该显示哪张幻灯片,显示幻灯片,并安排自己在将来再次运行。
当被调用时,返回函数调用logic 让球滚动。然后logic 无限期地重复,每次运行时都会安排自己在未来运行。
因此,总而言之,我们使用数字参数 x 调用 SlideChanger。它返回一个函数,在被调用后,将每x 秒更改一次幻灯片。
写相同概念的另一种方式。
(function(seconds_each) {
var index = -1;
// on the first cycle, index will be set to zero below
var maxindex = ($(".change_link").length) - 1;
// how many total slides are there (count the slide buttons)
return function() {
// this is the function returned by SlideChanger
var logic = function() {
// this is an inner function which uses the
// enclosed values (index and maxindex) to cycle through the slides
if (index == maxindex)
index = 0; // reset to first slide
else
index++; // goto next slide, set index to zero on first cycle
$('.slideshow').blinds_change(index); // this is what changes the slide
setTimeout(logic, 1000 * seconds_each);
// schedule ourself to run in the future
}
logic(); // get the ball rolling
}
})(5)(); // get the function at five seconds per slide and run it
JavaScript 是一种很好的语言,具有许多函数式编程结构,例如高阶函数(创建函数或接受函数作为参数的函数)和匿名函数。欲了解更多信息,请参阅http://www.ibm.com/developerworks/web/library/wa-javascript.html