-
new Function 的基础用法和常用demo
//有参数的 let sum = new Function('a', 'b', 'return a + b'); alert( sum(1, 2) ); // 3 // 没有参数的 let sayHi = new Function("console.log('Hello')"); sayHi(); // Hello const sumOfArray = new Function( "return function(){ console.log('hello') };", )(); // 调用函数 sumOfArray();
-
new Function中 arguments 与常规函数的一些不同之处
function example(a, b, c) { console.log(arguments[0]); // 输出 a console.log(arguments[1]); // 输出 b console.log(arguments[2]); // 输出 c } example(10, 20, 30); //打印 10 20 30
let sum = new Function('a', 'b', 'return a + b'); // 这里 a 和 b 是函数参数名。 arguments[0] 就是'return a + b'
-
new function 比对eval的区别
-
作用域:
- eval 在调用它的当前作用域内执行代码,可以访问和修改当前作用域中的变量和函数。
- new Function 创建的新函数在独立的全局作用域内执行,不能访问和修改外部作用域中的变量和函数。
-
性能:
- eval 会导致性能下降,因为代码解析和执行都需要在运行时进行。
- new Function 允许引擎进优化,性能优于 eval,但仍然不如静态代码高效。
-
安全性:
- eval 存在较高的安全风险,如果输入不可信的数据可能会造成严重安全漏洞。
- new Function 则相对更为安全,因为它只能访问全局作用域中的内容,不会直接影响外部作用域。
-
-
new Function 的应用场景有哪些
let _Function = Function; Function.prototype.constructor = function() { if (arguments[0].indexOf('debugger') != -1) { return _Function(''); } return _Function(arguments[0]); };
// 用户输入的查询条件 const queryCondition = "return obj.age > 30 && obj.country === 'USA';"; // 动态生成一个查询函数 const queryFunc = new Function('obj', queryCondition); // 用于查询的JSON数据 const data = [ { name: 'Alice', age: 35, country: 'USA' }, { name: 'Bob', age: 28, country: 'UK' }, { name: 'Charlie', age: 40, country: 'USA' } ]; // 动态过滤数据 const result = data.filter(queryFunc); console.log(result); // [{ name: 'Alice', age: 35, country: 'USA' }, { name: 'Charlie', age: 40, country: 'USA' }]
const expression = "data.a + data.b"; const compute = new Function('data', `return ${expression}`); console.log(compute({a: 1, b: 2})); // 输出 3
//示例片段 "methods": { "loadData": { "type": "JSFunction", "value": "function loadData(pageNum) {\nreturn this.$ss.index.default.prototype.loadData.apply(this, Array.prototype.slice.call(arguments));\n}" }, "onSelectChange": { "type": "JSFunction", "value": "function onSelectChange(selectedKeys, selectedRows) {\nreturn this.$ss.index.default.prototype.onSelectChange.apply(this, Array.prototype.slice.call(arguments));\n}" }, }
-
new Function 不太合适的场景和弊端注意点
在将 JavaScript 发布到生产环境之前,需要使用 压缩程序(minifier) 对其进行压缩。new Function需要通过显式传递参数的方式更加安全、可控
let userName = "John";
const func = new Function("return userName;");
//压缩之后 Function中的userName会变成a或b 之类 和上面的变量对应不上 导致报错