Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"new" Before Anonymous Function Invocation Returning Object [duplicate]

Tags:

javascript

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.

like image 210
Benjamin Gruenbaum Avatar asked May 18 '13 19:05

Benjamin Gruenbaum


People also ask

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

Can callbacks be anonymous functions?

As we can see, the callback function here has no name and a function definition without a name in JavaScript is called as an “anonymous function”. This does exactly the same task as the example above.

Can an anonymous function be recursive?

Even without mechanisms to refer to the current function or calling function, anonymous recursion is possible in a language that allows functions as arguments. This is done by adding another parameter to the basic recursive function and using this parameter as the function for the recursive call.

Is IIFE an anonymous function?

IIFE: Immediately Invoked Function ExpressionsThe example defines an anonymous function that is immediately invoked.


1 Answers

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"
like image 55
Jan Turoň Avatar answered Oct 10 '22 22:10

Jan Turoň