10

I'm reading the KnockoutJS source code.

I ran into the following line which I'm not sure I understand...

ko.utils = new (function () {

Generally, the structure seems to be along the lines of:

ko.utils = new (function () {

   // some variables declared with var

   return {
        export:value,
        export:value
   };

})();

I don't understand this construct, why is new needed? What does it do? What is it useful for?

(I thought that if a function is called with new before its name it is invoked as a constructor, and if it returns an object it's identical to an invokation without new.)

UPDATE: I asked the KnockoutJS team on github and this is what I got back:

My guess is that Steve just didn't know that it wasn't needed. Looking back at his original commit, I see a lot of unnecessary news that have since been removed.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 1
    As far as I can tell, the `new` has no effect in this case – John Dvorak May 18 '13 at 19:39
  • Related: [Is it right to think of a Javascript Function Expression that uses the 'new' keyword as 'static'](http://stackoverflow.com/questions/10406552/is-it-right-to-think-of-a-javascript-function-expression-that-uses-the-new-key) – Bergi Apr 08 '14 at 10:18
  • Just happened to come across both of them… – Bergi Sep 29 '16 at 15:50

1 Answers1

10

It might be some pattern which prevents this to reach the global context (not in this case, since every variable is declared var, but the author might wanted to use it as a general pattern to create objects).

var x = new (function () {
   this.foo = "bar";
   return {
        // whatever
   };
})();

console.log(foo); // Uncaught ReferenceError: foo is not defined 

var x = (function () { // without new
   this.foo = "bar";
   return {
        // whatever
   };
})();

console.log(foo); // "bar"
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
  • +1 That's very clever :) (of you to figure out that reasoning). The sort of thing `"use strict";` avoids. That's completely satisfactory, thanks. – Benjamin Gruenbaum May 18 '13 at 19:56