2015-12-15 191 views
0

我已閱讀關於命名空間函數的示例,例如here。但是這隻適用於一個單一的命名空間而不是多個。如何在多個命名空間中命名空間函數?

例如,我想爲我的根名稱空間爲「myLib」的助手函數創建自己的庫。然後MyLib中,它具有例如數學(額外的數學函數)和dateExtend多個命名空間(附加日期函數)

然後我想打電話給我的數學函數,例如像這樣:

myLib.math.hypotenus(10,10); //Returns 14.1421...

我已經想出了自己的解決方案,但我不知道這是不好的做法/錯誤。

這裏是我的代碼:

var myLib = new function() 
 
{ 
 
    this.dateExtend = new function() 
 
    { 
 
    this.toDayString = function(day){...} 
 
    this.toMonthString = function(month){...} 
 
    } 
 

 
    this.math = new function() 
 
    { 
 
    this.clamp = function (value, minValue, maxValue) {...} 
 
    this.hypotenus = function (width, height) {...} 
 
    } 
 
} 
 

 
console.log("Day: " + myLib.dateExtend.toDayString(1)); //Monday 
 
console.log("Hypotenus: " + myLib.math.hypotenus(10, 10)); //14.1421

在這裏,我已經做出了單變量,我可以在任何地方使用。這是好的/壞的編程習慣?

它的作品,我認爲它看起來很漂亮,我可以嵌套儘可能多的命名空間,因爲我想。

回答

2

new function(){…} is definitevely a bad practice。只需使用對象文字(或您鏈接的文章中的任何其他圖案),就可以輕鬆地嵌套這些對象:

var myLib = { 
    dateExtend: { 
     toDayString: function(day) {…}, 
     toMonthString: function(month) {…} 
    }, 
    math: { 
     clamp: function(value, minValue, maxValue) {…}, 
     hypotenus: function(width, height) {…} 
    } 
};