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.

0

1 Answer 1

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) {…}
    }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.