2013-01-02 17 views
2

考慮關於發表在Code Organization section of the Learning Center模塊模式的最後一個代碼段(下面報道),我試圖理解在示例中,模塊的某些方面:瞭解jQuery的教程模塊模式例如

  • 的變量聲明($items$container ...)由;分開,而函數聲明(createContainer,buildUrl,showItem,....)由,分隔。爲什麼?有支架問題嗎?
  • 爲什麼前三個變量的名稱($items$container$currentItem)以$開頭?這是否意味着命名約定(因爲javascript允許字符$)用於標識DOM片段變量或者是否存在其他原因?
  • 爲什麼函數createContainer使用var聲明,而其他函數(buildUrl,showItem,...)沒有var

//使用模塊模式的一個jQuery功能 $(文件)。就緒(函數(){

var feature = (function() { 

var $items = $("#myFeature li"); 
var $container = $("<div class='container'></div>"); 
var $currentItem = null; 
var urlBase = "/foo.php?item="; 
var createContainer = function() { 
    var $i = $(this); 
    var $c = $container.clone().appendTo($i); 
    $i.data("container", $c); 
}, 
buildUrl = function() { 
    return urlBase + $currentItem.attr("id"); 
}, 
showItem = function() { 
    var $currentItem = $(this); 
    getContent(showContent); 
}, 
showItemByIndex = function(idx) { 
    $.proxy(showItem, $items.get(idx)); 
}, 
getContent = function(callback) { 
    $currentItem.data("container").load(buildUrl(), callback); 
}, 
showContent = function() { 
    $currentItem.data("container").show(); 
    hideContent(); 
}, 
hideContent = function() { 
    $currentItem.siblings().each(function() { 
    $(this).data("container").hide(); 
    }); 
}; 
$items.each(createContainer).click(showItem); 

return { 
    showItemByIndex: showItemByIndex 
}; 

})(); 

feature.showItemByIndex(0); 
}); 

回答

1
  1. 可以申報多個語句或僅在1個變量, (var x;var y; vs var x,y;)。據我所知,沒有區別

  2. 以$開頭:是開發人員選擇,對於PHP程序員來說更好,不影響變量,沒什麼特別的,只是一個命名約定。我不使用它,我不推薦它,它只會讓你的代碼看起來最糟糕,如果你使用jQuery會給你更多headeaches。

  3. 見點1(它有 「無功」,但它在聲明的開頭):

    VAR createContainer =函數(){...},buildUrl =函數(){。 ...},showItem = function(){...},showItemByIndex = function(idx){...} ...;

看到更多細節的http://www.w3schools.com/js/js_variables.asphttp://www.wikihow.com/Declare-a-Variable-in-Javascript