【问题标题】:How to namespace functions in multiple namespaces?如何在多个命名空间中命名函数?
【发布时间】:2016-03-20 18:12:54
【问题描述】:

我已经阅读了有关命名空间的信息,例如 here。但这仅适用于单个命名空间,而不适用于多个命名空间。

例如,我想为我的根命名空间为“myLib”的辅助函数创建自己的库。然后在 myLib 中,它有更多的命名空间,例如 math(用于附加数学函数)和 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

在这里,我创建了一个可以在任何地方使用的单例变量。这是好的/坏的编程习惯吗?

它有效,我认为它看起来很漂亮,我可以嵌套任意数量的命名空间。

【问题讨论】:

    标签: javascript function namespaces singleton


    【解决方案1】:

    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) {…}
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      • 2011-03-15
      相关资源
      最近更新 更多