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.
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.
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.
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.
IIFE: Immediately Invoked Function ExpressionsThe example defines an anonymous function that is immediately invoked.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With