Organizing my JavaScript function library

Over time, I created a bunch of different JavaScript functions. Most of them are static functions and do things such as changing the date of a date, creating a menu for selecting HTML from an array, etc.

Currently, I have them all in a file called general.js, which, in turn, is directly called by my HTML page, and each of them looks something like this:

function modifyDate(data){....} function makeArray(arr){....} 

And then I use them like:

 alert(modifyDate("12/14/2013")); 

I think this is a bad idea, as it may contradict other libraries. Instead, I think of something like the following:

 myLibrary={}; myLibrary.modifyDate= function(data){....} myLibrary.makeArray= function(arr){....} 

And they use them like:

 alert(myLibrary.modifyDate("12/14/2013")); 

Notice that I kind of do it when I go. Please provide recommendations on how to best organize your JavaScript library. thank you

+4
source share
1 answer

What you are describing is called namespacing and is usually considered a good idea.

You can find a more detailed discussion of the namespace in this question: Why do they use namespaces in javascript?

In general, the advantages of a namespace are as follows:

  • Limiting global pollution and preventing name conflicts.
  • Providing context for the names of your functions (we expect different results for WindowUtils.getHeight and MenuUtils.getHeight ).

Thus, your example will provide the first advantage, although not necessarily the second, if it is just a group of grab-bag functions. It does not matter whether it is good or not, it completely depends on your individual project and what you are trying to do.

Please note that if you intend to use a namespace, you may need to examine the module template, which is a way to protect the scope of your namespaces to allow private variables / protected state. Here is a good example in this answer to a similar question , or you can check this canonical blog post on the module template

In your case, the module template will look something like this:

 var myLibrary=(function(){ var privateVariable; //accessible by your functions but not in the global context return { modifyDate: function(data){....}, myLibrarymakeArray: function(arr){....} }; }()) 
+8
source

All Articles