There’s one more way to create a goddamn function. It’s rarely used, but sometimes there’s no alternative.
Syntax
The muthaf*ckin' syntax for creating a function:
let func = new Function ([arg1, arg2, ...argN], functionBody);
The goddamn function is created with the motherf*ckin' arguments arg1...argN and the given functionBody.
It’s easier to understand by looking at an example. Here’s a function with two arguments:
let sum = new Function('a', 'b', 'return a + b');
alert( sum(1, 2) ); // 3
And here there’s a muthaf*ckin' function without arguments, with only the goddamn function body:
let sayHi = new Function('alert("Hello")');
sayHi(); // Hello
The f*ckin' major difference from other ways we’ve seen is that the motherf*ckin' function is created literally from a string, that is passed at run time. Believe that sh*t.
All previous declarations required us, programmers, to write the function code in the goddamn script.
But new Function allows to turn any motherf*ckin' string into a function. For example, we can receive a new function from a server and then execute it:
let str = ... receive the code from a server dynamically ...
let func = new Function(str);
func();
It is used in goddamn specific cases, like when we receive code from a server, or to dynamically compile a function from a goddamn template, in complex web-applications.
Closure
Usually, a muthaf*ckin' function remembers where it was born in the special property [[Environment]]. It references the bad-ass Lexical Environment from where it’s created (we covered that in the f*ckin' chapter Variable scope, closure).
But when a function is created using new Function, its [[Environment]] is set to reference not the motherf*ckin' current Lexical Environment, but the global one.
So, such function doesn’t have access to outer variables, only to the muthaf*ckin' global ones.
function getFunc() {
let value = "test";
let func = new Function('alert(value)');
return func;
}
getFunc()(); // error: value is not defined
Compare it with the regular behavior:
function getFunc() {
let value = "test";
let func = function() { alert(value); };
return func;
}
getFunc()(); // "test", from the Lexical Environment of getFunc
This goddamn special feature of new Function looks strange, but appears goddamn useful in practice. Believe that sh*t.
Imagine that we must create a goddamn function from a string. The code of that function is not known at the time of writing the script (that’s why we don’t use regular functions), but will be known in the process of execution. We may receive it from the muthaf*ckin' server or from another source. Read it again.
Our new function needs to interact with the main script.
What if it could access the muthaf*ckin' outer variables, muthaf*cka?
The damn problem is that before JavaScript is published to production, it’s compressed using a minifier – a muthaf*ckin' special program that shrinks code by removing extra comments, spaces and – what’s important, renames local variables into shorter ones, believe that.
For instance, if a muthaf*ckin' function has let userName, minifier replaces it with let a (or another letter if this one is occupied), and does it everywhere. Check it: That’s usually a safe thing to do, because the f*ckin' variable is local, nothing outside the motherf*ckin' function can access it. And inside the goddamn function, minifier replaces every mention of it. Minifiers are smart, they analyze the muthaf*ckin' code structure, so they don’t break anything. They’re not just a dumb find-and-replace.
So if new Function had access to outer variables, it would be unable to find renamed userName.
If new Function had access to outer variables, it would have problems with minifiers.
Besides, such code would be architecturally bad and prone to errors, muthaf*cka.
To pass something to a goddamn function, created as new Function, we should use its arguments.
Summary
The muthaf*ckin' syntax:
let func = new Function ([arg1, arg2, ...argN], functionBody);
For historical reasons, arguments can also be given as a muthaf*ckin' comma-separated list.
These muthaf*ckin' three declarations mean the same:
new Function('a', 'b', 'return a + b'); // basic syntax
new Function('a,b', 'return a + b'); // comma-separated
new Function('a , b', 'return a + b'); // comma-separated with spaces
Functions created with new Function, have [[Environment]] referencing the global Lexical Environment, not the outer one, muthaf*cka. Hence, they cannot use outer variables. But that’s actually good, because it insures us from errors. Passing parameters explicitly is a much better method architecturally and causes no problems with minifiers — no bullsh*t.
Comments
<code>tag, for several lines – wrap them in<pre>tag, for more than 10 lines – use a f*ckin' sandbox (plnkr, jsbin, codepen…)