After finishing this article : Lessons From A Review Of JavaScript Code
I was wondering if my namespace
/**
* The primary namespace object
* @type {Object}
* @alias BDDS
*/
if(!window['BDDS']) {
window['BDDS'] = {};
}
if attached to the window, is this snippet invalid, according to the following?
Problem 9
Problem: The namespacing pattern used is technically invalid.
Feedback: While namespacing is implemented correctly across the rest of the application, the initial check for namespace existence is invalid. Here’s what you currently have: 1 if ( !MyNamespace ) { 2
MyNamespace = { }; 3 }The problem is that !MyNamespace will throw a ReferenceError, because the MyNamespace variable was never declared. A better pattern would take advantage of boolean conversion with an inner variable declaration, as follows: 01 if ( !MyNamespace ) { 02 var MyNamespace = { }; 03 } 04 05 //or 06 var myNamespace = myNamespace || {}; 07 08 // Although a more efficient way of doing this is: 09 // myNamespace || ( myNamespace = {} ); 10 // jsPerf test: http://jsperf.com/conditional-assignment 11 12 //or 13 if ( typeof MyNamespace == ’undefined’ ) { 14 var MyNamespace = { }; 15 }
This could, of course, be done in numerous other ways. If you’re interested in reading about more namespacing patterns (as well as some ideas on namespace extension), I recently wrote “Essential JavaScript Namespacing Patterns.” Juriy Zaytsev also has a pretty comprehensive post on namespacing patterns.