2011-08-12 33 views
1

我是一個典型的Web開發人員,他在JS中使用全局的東西。我現在已經看到了燈光並想轉換爲命名空間。所以在我目前的項目中,我有一個頁面有三個JS函數(當前全部是全局的),當調用將文本分配給錨點並附加點擊方法來切換特定div的可見性時。非常標準。JavaScript轉換爲名稱空間和調用函數

所以一個例子函數寫爲:

function toggleComments(){ 
    $("comments-section").hide(); 
    $("comments-button").click(function(){ 
     blah 
     return false; 
    }); 
} 

我的問題是我如何創建一個命名空間來容納這些功能,然後給他們打電話?

我發現了不同的例子,但沒有定論。

任何幫助將是偉大的。

回答

1

比利月亮示出一個好的開始,但是使用對象文字的問題,就是可以不交叉引用其他字段/功能/特性。

我更喜歡顯露模塊模式(見http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/

透露出模塊模式結合了閉包來提供內部私有函數/字段的自動執行功能,(各種)的開發,並允許您傳遞參數來初始化命名空間對象。

var namespacedObject = function(param) { 

    var settings = param || someDefaultSetting, //default if no param supplied 
     somePrivateField = "someValue", 
     somePublicField = "i'm public"; 

    //define some method we will later make public 
    function toggleComments(){ 
     $("comments-section").hide(); 
     $("comments-button").click(function(){ 
      $(this).value= somePrivateField; 
      return false; 
     }); 
    } 

    //this is where the magic happens, 
    //return object with all public fields/functions 
    return { 
     toggleComments : toggleComments, 
     somePublicField : somePublicField 
    }; 

}(someParam); 

您可以看到命名空間的對象包含私有字段somePrivateField,這可以從可公開訪問的方法引用。另外,請注意我已經露出了公共領域,並接受了一些PARAMS,我可以使用功能等/引用(你可以,如果沒有在傳遞它默認爲一些默認

可以這樣使用:

namespacedObject.toggleComments(); 
alert(namespacedObject.somePublicField); 
alert(namespacedObject.somePrivateField); //undefined - it's private of course! 

一個原因,我想這是它很容易看到什麼是公共/私人通過在從自動執行功能

希望這是有幫助返回的對象字面只是看了一眼

2
// choos a namespace name that will not conflict with existing global variables 
var myNS = { 
     toggleComments: function(){ 
      $("comments-section").hide(); 
      $("comments-button").click(function(){ 
       // blah 
       return false; 
      }); 
     }, 
     anotherFunc: function(){ 
      return "something"; 
     } 
} 

// called like this 
myNS.toggleComments(); 
alert(myNS.anotherFunc()); 

此外,您應該嘗試將您的代碼包含在匿名自調用函數中。這意味着您可以在全局名稱空間中沒有任何內容,因此沒有污染風險。

// other peoples/modules code 
var myVariable = "whatever"; 

// anonymous function for your self contained code 
(function(){ 
var myVariable = "inside anonymous function"; 
alert(myVariable); 
})() // the empty brackets envoke the anonymous function 

// still retains value from before your self envoking anonymous function 
alert(myVariable);