Guest User

Untitled

a guest
Jan 21st, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. // This code original author is Stoyan Stefanov
  2.  
  3. // top-level namespace being assigned an object literal
  4. var myApp = myApp || {};
  5. // a convenience function for parsing string namespaces and
  6. // automatically generating nested namespaces
  7. function extend( ns, ns_string ) {
  8. var parts = ns_string.split('.'),
  9. parent = ns,
  10. pl, i;
  11. if (parts[0] == "myApp") {
  12. parts = parts.slice(1);
  13. }
  14. pl = parts.length;
  15. for (i = 0; i < pl; i++) {
  16. //create a property if it doesnt exist
  17. if (typeof parent[parts[i]] == 'undefined') {
  18. parent[parts[i]] = {};
  19. }
  20. parent = parent[parts[i]];
  21. }
  22. return parent;
  23. }
  24. // sample usage:
  25. // extend myApp with a deeply nested namespace
  26. var mod = extend(myApp, 'myApp.modules.module2');
  27. // the correct object with nested depths is output
  28. console.log(mod);
  29. // minor test to check the instance of mod can also
  30. // be used outside of the myApp namesapce as a clone
  31. // that includes the extensions
  32. console.log(mod == myApp.modules.module2); //true
  33. // further demonstration of easier nested namespace
  34. // assignment using extend
  35. extend(myApp, 'moduleA.moduleB.moduleC.moduleD');
  36. extend(myApp, 'longer.version.looks.like.this');
  37. console.log(myApp);
Add Comment
Please, Sign In to add comment