tags:

views:

79

answers:

2

Hi

In javascript, what is the difference between:

var singleton = function(){ ... }

and

var singleton = new function(){ ... }

?

Declaring priviliged functions as described by crockford (http://www.crockford.com/javascript/private.html) only works using the latter.

+5  A: 

The difference is mainly that in your second example, you are using the Function Expression as a Constructor, the new operator will cause the function to be automatically executed, and the this value inside that function will refer to a newly created object.

If you don't return anything (or you don't return a non-primitive value) from that function, the this value will be returned and assigned to your singleton variable.

Privileged methods can also be used in your second example, a common pattern is to automatically invoke the function, creating a closure where the private members are accessible, then you can return an object that contains your public API, e.g.:

var singleton = (function () {
  var privateVar = 1;

  function privateMethod () {/*...*/}

  return { // public API
    publicMethod: function () {
      // private members are available here
    }
  };
})();
CMS
Great answer! +1
Jacob Relkin
you nailed it...
jd
A: 

I think that a privileged function as described by crockford would look like this:

function Test() {
     this.privileged = function() {
          alert('apple');
     }
     function anonymous() {
         alert('hello');
     }
     anonymous();
}

t = new Test; // hello
t.privileged(); // apple

// unlike the anonymous function, the privileged function can be accessed and
// modified after its declaration

t.privileged = function() {
     alert('orange');
}

t.privileged(); // orange
mattwindwer
That is a privileged function indeed, but not a singleton.
jd