1 回答

TA貢獻1798條經驗 獲得超3個贊
是可以當做構造函數來用的
var adder = new Function('a', 'b', 'return a + b');// Call the functionadder(2, 6);// > 8
區別的話,用構造函數生成的函數不會有閉包,他們只能訪問自身作用域和全局作用域聲明的變量和函數。其他詳細的地方參考MDN
Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using eval with code for a function expression.
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
添加回答
舉報