How can I create an empty namespace object without overwriting another object with the same name?

前端 未结 3 1633
南旧
南旧 2021-01-23 10:51

I have been studying as much as I can about the Module Pattern suggested by the Yahoo YUI Blog.

I\'ve noticed that the YUI offers the ability to create a new empty names

3条回答
  •  忘掉有多难
    2021-01-23 11:40

    Edit Just realized I'm not directly answering your question. Sorry! However hopefully this will help you understand some alternate techniques.

    This is a technique I use from time to time, such as when I want to add a property or function once and not allow it to be overwritten later.

        var module = new function(){
    
            var modules = {}; //internal module cache
    
            return function(name, module){
                //return all modules
                if( !name ) return modules;
    
                //return specific module
                if( modules[name] ) return modules[name];
    
                //return the module and store it
                return modules[name] = module;
            }
    
        }
    

    So you can use it like so:

    //will store this since it doesn't exist
    module('test', 'foo'); //Since 'test' doesn't exist on the internal 'modules' variable, it sets this property with the value of 'foo'
    
    module('test'); // Since we aren't passing a 2nd parameter, it returns the value of 'test' on the internal 'modules' variable
    
    module('test', 'bar'); //We are attempting to change the value of 'test' to 'bar', but since 'test' already equals 'foo', it returns 'foo' instead.
    
    module(); // { 'test': 'foo' } //Here we aren't passing any parameters, so it just returns the entire internal 'modules' variable. 
    

    The key thing to look at is that we're using 'new function()'. This is done at assignment, because we really want 'module' to be the internal function, not the outer. But in order to create a closure for the internal 'var modules' variable, the outer function has to execute on assignment.

    Also notice that you could write the outer function to be self executing too:

    var module = function(){
        var modules = {};
        //other stuff
    }();
    

提交回复
热议问题