lixo.org

JavaScript: Put Everything in a Namespace

Yes, everything. Put it in a namespace. Everything. No exceptions and no excuses, unless yours is “I have just been thawed.” In this case, I want to be the first to warmly welcome you to the 21st century.

Here’s a simple and reasonably OK way to do it and be nice to your friends, other libraries and the world at large:


var Article = Article ? Article : new Object();
Article.title = "Report: School Shootings Help Prepare Students For Being Shot In Real World";
Article.save = function() {
alert("Saving " + this.title);
}


You could save a few keystrokes, though. Just use the object literal notation directly:


var Article = Article ? Article : {
title: "Report: School Shootings Help Prepare Students For Being Shot In Real World",
save: function() {
alert("Saving " + this.title)
}
}


These two last examples are great if you’re not that concerned about exposing the ‘title’ attribute to the rest of the world. If there is a chance that problems could arise if some other piece of code changed it directly, there is a solution:


var Article = Article ? Article : function() {
var private = {
title: "Report: School Shootings Help Prepare Students For Being Shot In Real World"
};

var public = {
getTitle: function() {
return private.title;
},

save: function() {
alert("Saving " + this.getTitle());
}
}

return public;
}();


I find this a bit hard to get used to, after so many years of developing in languages that explicitly allow me to set access control. It makes sense, though: by creating an anonymous function that returns the object I want to define, and then immediately calling it (note the ‘()’ at the last line), I can hide whatever I don’t want other parts of the code to see - it’s all tucked away in the local context of that anonymous function.