1

Code of horror:

var namespace = new function ()
{
    this.saySomething = new function( something )
    {
        console.log( something );
    };
}

namespace.saySomething( "whatever" );

This outputs "undefined" when I expected it to output "whatever". How come? And what would the fix be? My goal is nothing more than to have a namespace where I put some helper functions.

Martin Andersson
  • 18,072
  • 9
  • 87
  • 115

5 Answers5

3

new function is generally wonky. Rob W's answer is absolutely correct (+1'd), but I would personally go even further and remove all the newing:

var namespace = 
{
    saySomething: function( something )
    {
        console.log( something );
    }
}

namespace.saySomething( "whatever" );

If you want to be able to create distinct instances, do it the right way:

function Namespace() {}
Namespace.prototype.saySomething = function (something)
{
    console.log(something);
}

// Usage:
var foo = new Namespace();
foo.saySomething("Hallllooooo!");

...though you did say "singleton," so I'm guessing this isn't relevant to your goal.

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Thanx. Yeah you're right, the prototype object for me in this particular situation is a little bit overkill. And I never intended to create a full blown singleton pattern either. So that's why I mixed together the words in the topic like so: "namespace/singleton". Appreciate your answer! – Martin Andersson Apr 26 '12 at 20:11
2

Remove new before function(something){...}. Currently, saySomething is an instance of the anonymous constructor.

Rob W
  • 341,306
  • 83
  • 791
  • 678
2

You don't need to use new before the functions. new is only used for instantiating objects, when a constructor is already defined.

Your code should look like:

var namespace = {
    saySomething: function(something) {
        console.log(something);
    }
}

namespace.saySomething("whatever");
slowpoison
  • 586
  • 3
  • 20
  • I wouldn't use this method because somebody might use your namespace and can override and do namespace.saySomething = function( someotherthing ) { console.log( someotherthing ); /* and some more stuff here.*/ }. – vimdude Apr 29 '12 at 21:03
1

I would use something like the following because you also want to make sure that namespace doesn't get overridden by some other code.

var namespace = (function() {
      return {
          saySomething: function(something) {
               console.log(something);
          }
      };
})();

namespace.saySomething("whatever");
vimdude
  • 4,447
  • 1
  • 25
  • 23
0

This should do it, sample http://jsfiddle.net/Jssxy/

var namespace = {
    saySomething : function(something) {
        console.log(something);
    }
}

namespace.saySomething( "whatever" );​
Sully
  • 14,672
  • 5
  • 54
  • 79