Thursday, March 31, 2011

Javascript Namespacing, what am I doing wrong?

I'm taking an existing JS library I wrote up some time ago, and trying to organize it under a common namespace...Here is an example of the technique I am trying to use:

var NameSpace = new function ()
{
    var privateMember = [];

    function privateMethod() {};


    return 
    {  
     PublicMethod1 : function(arg, arg2)
     {
      // etc
     },
     PublicMethod2 : function ()
     {
      // etc
     },
     PublicMethod3 : function(arg, arg2)
     {
      // etc
     }
    }; 

}();

From what I can tell, this should work perfectly, however I get a Syntax Error on this line:

PublicMethod1 : function(arg, arg2)

Can anyone see some obvious problem with this technique?

From stackoverflow
  • var NameSpace= function ()
    {
        var privateMember = new Array();
    
        function privateMethod() { };
    
        return {           
            PublicMethod1 : function(arg, arg2)
            {
                    // etc
            },
            PublicMethod2 : function ()
            {
                    // etc
            },
            PublicMethod3 : function(arg, arg2)
            {
                    // etc
            }
        };  
    
    }();
    

    Problem was real tricky, return and { should be on the same line apparently. Also new [] was not valid, I fixed this for you too.

    FlySwat : It is somewhat ridiculous that JS is "whitespace agnostic" until it isn't.
    Matt Ephraim : JavaScript doesn't require a semicolon at the end of the line, so putting the opening bracket on the next line was making the function return before it could reach the bracket. I've been burned by that exact same gotcha.
  • just a quick note about the array assignment.

    This works: var privateMember = new Array();

    And this works, too: var privateMember = [];

    Of course, this doesn't: var privateMember = new [];

    Creating a singleton from the closure as in the original (correcting for the return positioning) is perfectly acceptable and doesn't need to be an instantiation of an object as in the second comment

0 comments:

Post a Comment