2013-01-02 18 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