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.
The difference is mainly that in your second example, you are using the Function Expression as a Constructor, the
newoperator will cause the function to be automatically executed, and thethisvalue 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
thisvalue will be returned and assigned to yoursingletonvariable.Privileged methods can also be used in your second example, a common pattern is use an immediately invoked function expression, creating a closure where the private members are accessible, then you can return an object that contains your public API, e.g.: