Creating Functions Using new Function
Syntax new Function ([arg1[, arg2[, …argN]],] functionBody)
Creating a function by using the constructor to generate a new instance has the following characteristics compared with function declarations:
- Functions can be created dynamically
- All functions are anonymous functions, and Function.name is always anonymous
- Local variables cannot be referenced inside the function; only global variables can be referenced
var x = 10;
function createFunction1() {
var x = 20;
return new Function("return x;"); // this |x| refers global |x|
}
function createFunction2() {
var x = 20;
function f() {
return x; // this |x| refers local |x| above
}
return f;
}
var f1 = createFunction1();
console.log(f1()); // 10
var f2 = createFunction2();
console.log(f2()); // 20
