views:

132

answers:

2

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?

+8  A: 
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.

Tomh
It is somewhat ridiculous that JS is "whitespace agnostic" until it isn't.
FlySwat
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.
Matt Ephraim
A: 

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

Jonathan Fingland