函数变量闭包

Function variable closure

本文关键字:闭包 变量 函数      更新时间:2023-09-26

这里有一个简单的滑块代码,我想了解变量函数闭包是如何工作的。。。

(function($) {
var sliderUL = $('div.slider').css('overflow', 'hidden').children('ul'),
    imgs = sliderUL.find('img'),
    imgWidth = imgs[0].width, // 600
    imgsLen = imgs.length, // 4
    current = 1,
    totalImgsWidth = imgsLen * imgWidth; // 2400
$('#slider-nav').show().find('button').on('click', function() {
    var direction = $(this).data('dir'),
        loc = imgWidth; // 600
    // update current value
    **( direction === 'next' ) ? ++current : --current;
    // if first image
    if ( current === 0 ) {
        current = imgsLen;
        loc = totalImgsWidth - imgWidth; // 2400 - 600 = 1800
        direction = 'next';
    } else if ( current - 1 === imgsLen ) { // Are we at end? Should we reset?
        current = 1;
        loc = 0;
    }
    transition(sliderUL, loc, direction);**
});
function transition( container, loc, direction ) {
    var unit; // -= +=
    if ( direction && loc !== 0 ) {
        unit = ( direction === 'next' ) ? '-=' : '+=';
    }
    container.animate({
        'margin-left': unit ? (unit + loc) : loc
    });
}
})(jQuery);

本部分:

    $('#slider-nav').show().find('button').on('click', function() {
    var direction = $(this).data('dir'),
        loc = imgWidth; // 600
    // update current value
    ( direction === 'next' ) ? ++current : --current;
    // if first image
    if ( current === 0 ) {
        current = imgsLen;
        loc = totalImgsWidth - imgWidth; // 2400 - 600 = 1800
        direction = 'next';
    } else if ( current - 1 === imgsLen ) { // Are we at end? Should we reset?
        current = 1;
        loc = 0;
    }
    transition(sliderUL, loc, direction);
});

在if(current==0)块中,变量current、loc和direction在第一个块中更改后是否更新,然后将它们传递给下面的转换函数?

我认为,如果else-if(current-1===imgsLen)为真,那么current和loc将重写之前分配给它们的值,然后传递到transitions函数中?

directionloc是在回调函数的作用域中定义的,用于"单击"。每次调用回调函数时,也就是每次单击时,都会初始化它们。direction由与按钮相关的"数据目录"初始化,loc初始化为imgWidth的当前值(这是在主函数范围内定义的变量)。

初始化后,directionloc可以由if-else if逻辑进行修改,然后将它们传递给函数transition()。(请注意,sliderIU也传递给transition(),但没有必要,因为它具有主函数的作用域,并且可以在transition()内直接使用,而不作为参数container传递。但是,将其作为参数传递可能不是一个坏主意,因为当您可以从函数的参数中看到它所作用的值时,它可以使编程风格更加清晰。)

回调点击函数中使用的变量current没有在该回调点击函数的作用域中定义,而是具有主函数作用域(在主函数开始时定义)。这是必要的,因为您希望在每次单击按钮时更改其值,并记住更改。回调点击函数是闭包,因为它可以访问(读+写)外部变量current。变量directionloc与闭包无关;它们只是传递给函数的变量。

您突出显示的代码的步骤如下:-从单击的按钮获取"dir"的值-将loc的默认值设置为图像的宽度(imgWidth)-如果方向是"下一个",则将电流加1,否则从当前中减去1

现在,在这一点上,我们可能会遇到电流可能为0或imgLen+1的情况。这两者都不是一个好的价值。因此,我们执行以下操作-如果电流为0-将current设置为imgsLen(转到最后一张图像)-将loc设置为最大可能有效值-设置方向="下一个"-如果当前图像超过最后一个图像-设置电流=0(转到第一个图像)-将loc设置为0(可能的最小有效值)-使用参数的更新值调用转换函数

希望这能回答你的问题。