Skip to content

Instantly share code, notes, and snippets.

@addyosmani
Created September 16, 2011 12:08
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save addyosmani/1221980 to your computer and use it in GitHub Desktop.
Save addyosmani/1221980 to your computer and use it in GitHub Desktop.
JavaScript object 'namespace' extension experiments
$(function(){
//===========================================================
// JavaScript object 'namespace' extension experiments
// by @addyosmani (comparing deep extension in vanilla JS vs.
// jQuery's $.extend)
//
//
// The goal here is to:
//
// (a) enable easier object namespace (and nested namespace)
// extension (eg. extend(namespace, nestedNamespace))
//
// (b) enable easier cached namespace extension (eg. var q =
// ns.module1.utils.foo.bar; q.module2 = {};)
//===========================================================
console.group("jQuery $.extend namespacing");
// base namespace
var myApp = myApp || {};
// 1. can we extend the namespace with a new sub-namespace called 'utils'?
$.extend(true, myApp, {
utils:{
}
});
console.log('test 1', myApp); //now contains utils
myApp.utils.test0 = 'hello world';
// 2. how about more depths?.
$.extend(true, myApp, {
hello:{
world:{
wave:{
}
}
}
});
myApp.hello.test1 = 'this is a test';
myApp.hello.world.test2 = 'this is another test';
console.log('test 2', myApp);
/*
as expected:
hello
test1
world
test2
wave
library
utils
*/
// 3. what if myApp already contains the namespace being added (eg. 'library')?
// we want to ensure no namespaces are being overridden
myApp.library = {
foo:function(){}
};
$.extend(true, myApp, {library:{ bar:function(){}}})
console.log('test 3', myApp); //now also contains library.foo, library.bar
// nothing has been overwritten which is what we're hoping for.
// 4. what if we wanted easier access to a specific namespace without having
// to type the whole namespace out each time?.
var shorterAccess = myApp.hello.world;
shorterAccess.test3 = "hello again";
console.log('test 4', myApp);
//success, myApp.hello.world.test3 is now 'hello again'
console.groupEnd();
});
@waltonryan
Copy link

This is great. But I've been trying to figure out how to create private variables with this method. Are you able to do that easily with this approach?

@waltonryan
Copy link

I think I've found an approach that works.

// top-level namespace
var ezdia = ezdia || {};
var namespace = ezdia.widget = ezdia.widget || {};

//create or extend widget
$.extend(true, namespace, function () {
    // private variables and methods
    var app = {
        init: function (data, options) {
                    // initialize widget
        }
      }
    };
    // public methods
    return {
               init: function () {
                    app.init(arguments);
        }
    }
}(jQuery));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment