Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organizing my JavaScript function library

Tags:

javascript

Over time, I created a bunch of various JavaScript functions. Most of them are static functions, and do things like modify the appears of a date, create the select menu HTML from an array, etc.

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

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

And then I use them as:

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

I am thinking this is a bad idea as it might conflict with other libraries. Instead, I am thinking of something like the following:

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

And them use them as:

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

Note that I am kind of making this up as I go. Please provide advice how I should best organize my JavaScript library. Thank you

like image 864
user1032531 Avatar asked Feb 17 '23 23:02

user1032531


1 Answers

What you're describing is called namespacing and is generally considered a good idea.

Some more discussion of namespacing can be found in this question: Why do they use namespaces in javascript?

In general the benefits of namespacing are:

  1. Limiting pollution of the global scope and preventing naming collisions
  2. Providing context for your function names (we'd expect different results for WindowUtils.getHeight and MenuUtils.getHeight for instance).

So your example would provide the first benefit, though not necessarily the second one if this is just a group of grab-bag functions. Whether thats a good thing or not is totally dependent on your individual project and what you're trying to do.

Note that if you're going to be namespacing, you may want to look into the module pattern which is a way of protecting the scope of your namespaces to allow for private variables/protected state. There's a good example in this answer to a similar question or you could check out this canonical blog post on the module pattern

In your case the module pattern would 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){....}
  };
}())
like image 190
Ben McCormick Avatar answered Mar 02 '23 19:03

Ben McCormick