[英]Function variable closure
這是一個簡單的滑塊代碼,我想了解變量函數閉包是如何工作的...
(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)為true,則將current和loc寫入分配給它們的先前值,然后將其傳遞給transitions函數?
您突出顯示的代碼的步驟如下:-從單擊的按鈕獲取'dir'的值-將loc的默認值設置為圖像的寬度(imgWidth)-如果方向為'next' ,然后將1加到當前,否則從當前減1
現在,在這一點上,我們可能會遇到當前電流可能為0或imgLen + 1的情況。 因此,我們執行以下操作-如果current為0-將current設置為imgsLen(轉到最后一個圖像)-將loc設置為最大可能的有效值-設置direction ='next'-如果電流超出最后一個image-設置current = 0 (轉到第一張圖片)-將loc設置為0(可能的最小有效值)-使用參數的更新值調用轉換函數
希望這能回答您的問題。
direction
和loc
在回調函數為“點擊”的范圍界定。 每次您調用該回調函數時都會對它們進行初始化-每次單擊。 direction
由與按鈕關聯的“數據目錄”初始化,而loc
初始化為imgWidth
的當前值(這是在主函數范圍內定義的變量)。
初始化后,可以通過if-else if
邏輯修改direction
和loc
,然后將它們傳遞給函數transition()
。 (請注意, sliderIU
也傳遞給transition()
,但這不是必需的,因為它具有您的主要功能的范圍,並且可以直接在transition()
而無需作為參數container
傳遞。但是,這可能不是一個壞問題。想法將其作為參數傳遞,因為當您從函數的參數上看到它所作用的值時,它可以使編程風格更加清晰。)
在callback-click函數的作用域中未定義該變量current
,而是在main函數作用域中定義(在main函數的開始處定義)。 這是必要的,因為您想在每次單擊按鈕時更改其值-並記住更改。 callback-click函數是一個閉包,因為它可以訪問(讀+寫)外部變量current
。 變量direction
和loc
與閉包無關。 它們只是您傳遞給函數的變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.