0

I have read about namespacing a function for example here. But this works only for one single namespace and not multiple.

For example, i want to make my own library for helper functions where my root namespace is "myLib". Then in myLib, it has more namespaces for example math (for additional math functions) and dateExtend (for additional date functions)

Then i want to call my math functions for example like this:

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

I have come up with my own solution, but i dont know if this is bad practice/wrong.

Here is my code:

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

Here i have made a singleton variable which i can use anywhere. Is this good/bad programming practice?

It works and i think it looks pretty and i can nest as many namespaces as i want.

thanksd
  • 54,176
  • 22
  • 157
  • 150
Assassinbeast
  • 1,207
  • 1
  • 17
  • 33

1 Answers1

2

new function(){…} is definitevely a bad practice. Just use an object literal (or any other of the patterns in the article you linked), you can nest those just as easily:

var myLib = {
    dateExtend: {
        toDayString: function(day) {…},
        toMonthString: function(month) {…}
    },
    math: {
        clamp: function(value, minValue, maxValue) {…},
        hypotenus: function(width, height) {…}
    }
};
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375