6

I have the following function

var myInstance =  (function() {
  var privateVar = 'Test';

  function privateMethod () {
    // ...
  }

  return { // public interface
    publicMethod1: function () {
      // all private members are accesible here
        alert(privateVar);
    },
    publicMethod2: function () {
    }
  };
})();

what's the difference if I add a new to the function. From firebug, it seems two objects are the same. And as I understand, both should enforce the singleton pattern.

var myInstance =  new (function() {
  var privateVar = 'Test';

  function privateMethod () {
    // ...
  }

  return { // public interface
    publicMethod1: function () {
      // all private members are accesible here
        alert(privateVar);
    },
    publicMethod2: function () {
    }
  };
})();
J.W.
  • 16,815
  • 6
  • 40
  • 75
  • 2
    [What the the "new" keyword in JavaScript?](http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript) – mplungjan Jun 24 '11 at 12:46

1 Answers1

8

While the end result seems identical, how it got there and what it executed in is different.

The first version executes the anonymous function with this being in the context of the window object. The second version executes the anonymous function, but this is in the context of a new empty object.

In the end, they both return another object(your Singleton). It's just a slight difference in execution context.

To test this out, but an alert(this); right before the declaration of the privateVar variable.

@Tom Squires: That's not necessarily true and is poor practice not to declare your variables. A script with the "use strict"; directive does cause the JS engine to complain (assuming that the engine supports "use strict";

Dino Gambone
  • 535
  • 3
  • 10