-
-
Save webxl/1235550 to your computer and use it in GitHub Desktop.
JavaScript object 'namespace' extension experiments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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(); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment