JavaScript Namespace Declaration

后端 未结 8 1875
既然无缘
既然无缘 2020-12-07 15:09

I created a javascript class as follow:

var MyClass = (function() {
   function myprivate(param) {
      console.log(param);
   }

   return {
      MyPublic         


        
相关标签:
8条回答
  • 2020-12-07 15:46

    A succinct way to do what you're asking is create "Namespace" as an object literal like this:

    var Namespace = {
        MyClass : (function() {
            ... rest of your module
        })();
    };
    

    This could cause conflicts if you wanted to attach other details to Namespace in other files, but you could get around that by always creating Namespace first, then setting members explicitly.

    0 讨论(0)
  • 2020-12-07 15:46

    Automating namespaces declaration in javascript is very simple as you can see:

    var namespace = function(str, root) {
        var chunks = str.split('.');
        if(!root)
            root = window;
        var current = root;
        for(var i = 0; i < chunks.length; i++) {
            if (!current.hasOwnProperty(chunks[i]))
                current[chunks[i]] = {};
            current = current[chunks[i]];
        }
        return current;
    };
    
    // ----- USAGE ------
    
    namespace('ivar.util.array');
    
    ivar.util.array.foo = 'bar';
    alert(ivar.util.array.foo);
    
    namespace('string', ivar.util);
    
    ivar.util.string.foo = 'baz';
    alert(ivar.util.string.foo); 
    

    Try it out: http://jsfiddle.net/stamat/Kb5xY/ Blog post: http://stamat.wordpress.com/2013/04/12/javascript-elegant-namespace-declaration/

    0 讨论(0)
提交回复
热议问题