The Function() constructor creates Function objects.
Calling the constructor directly can create functions
dynamically, but suffers from security and similar
(but far less significant) performance issues as eval().
However, unlike eval (which may have access to the local scope),
the Function constructor creates functions which execute in the
global scope only.
syntax:
let func = new Function ([arg1, arg2, ...argN], functionBody);
with parametrers:
let sum = new Function('a', 'b', 'return a + b');
alert( sum(1, 2) ); // 3
Without parameters:
let sayHi = new Function('alert("Hello")');
sayHi(); // Hello
Creating Funcion dynamically:
new Function allows to turn any 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();
such function doesn’t have access to outer variables, only to the global ones.
let value = "test";
let func = new Function('console.log(value)');
return func;
}
getFunc()(); // error: value is not defined
Output:
We get error saying
ReferenceError: value is not defined
Comparing function of new Function with normal function:
Here is a normal function with similar implementation
Code:
function getFunc() {
let value = "test";
let func = function () {
console.log(value);
};
return func;
}
getFunc()(); // "test", from the Lexical Environment of getFunc
Output:
test
If new Function had access to outer variables:
if a function has let userName, minifier replaces it with let a
(or another letter if this one is occupied), and does it everywhere.
That’s usually a safe thing to do,because the variable is local,
nothing outside the function can access it. And inside the function,
minifier replaces every mention of it. Minifiers are smart, they
analyze the 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.
No comments:
Post a Comment