Create a “locked initializer” for your JavaScript namespace
Because JavaScript is class-free, you lose the benefit of executing code in a classical constructor before an object is instantiated (referenced/invoked). Do not misunderstand me — you can actually execute code because all functions are constructors, but not in the traditional OOP sense. For instance, the following is a constructor that executes code when the object is referenced.
function myConstructor() {
alert( "Constructor!" );
}
var myObject = new myConstructor();
This is a very simple example, and it will be more difficult to maintain design integrity as the code executed grows in size. If you have a library namespace, an object literal, and public and private methods, then it becomes important to consider an alternate method. You might have use for what I will call a “locked initializer”.
It is a locked initializer because it only runs once before your library namespace object is self-invoked, and it is inaccessible to other methods in your code. This is because it, too, is self-invoked. Here is some code similar to how most JavaScript libraries are designed, with the locked initializer in place. For this example, the library namespace is called HAL.
var HAL = window.HAL ? HAL : function() {
var init = function() {
alert( "Initialized!" );
}();
var privateObject = {
privateMethod: function() {
alert( "Private Method!" );
}
};
return {
privilegedMethod: function() {
return privateObject.privateMethod();
},
publicMethod: function() {
return alert( "Public Method!" );
},
publicProperty: null
};
}();
HAL.privilegedMethod();
HAL.publicMethod();
It is rare that you would want to execute code before your namespace even exists. An occasion where it might come in handy is in a mashup. You could ping a third-party API to verify it is running before loading up the entire library. You might also place object or browser detectors within the initializer. Just like a constructor in classical OOP, the point is to get something done before the object is referenced.
Leave a Comment
Comments are moderated. No profanity. Only <a>...</a>, <blockquote>...</blockquote>, and <code>...</code> are allowed.
Seperate paragraphs by pressing the "Enter" key twice, or press it once to break to a new line.
2 Comments
#01, Oct 18 2007
Oncle Tom
Interesting as always. I think closures and scopes are the hardest things in JS. Your example explain it very simply and I like that.
It’s the “Singleton” design pattern no ?
#02, Oct 19 2007
Brian
Hi Oncle Tom,
Good to hear from you again. This is one way of creating a Singleton in JavaScript. You will be unable to instantiate another HAL, primarily because HAL is not a constructor.
Brian