public
Last active

JavaScript object 'namespace' extension experiments

  • Download Gist
objExtend.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
$(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();
 
 
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.