JS
1. eval
eval() 是一个全局函数,用于执行字符串形式的JavaScript代码。
let code = "console.log('Hello from eval!')"; eval(code); // 输出: Hello from eval! let x = 10; let y = 20; let result = eval("x + y"); // result = 30
特点:
执行字符串中的代码
可以访问当前作用域中的变量
安全隐患:容易导致代码注入攻击
性能问题:无法被JavaScript引擎优化
现代开发中通常避免使用
2. Function
Function 是一个构造函数,用于创建新的函数对象。
// 通过Function构造函数创建函数 const add = new Function('a', 'b', 'return a + b'); console.log(add(2, 3)); // 输出: 5 // 等同于 const add = function(a, b) { return a + b; };
语法:
new Function([arg1[, arg2[, ...argN]],] functionBody)
特点:
在全局作用域中创建函数,无法访问局部变量
比 eval 更安全,但仍然需要谨慎使用
可用于动态生成函数
3. Function.prototype.constructor
Function.prototype.constructor 是Function原型对象的构造器属性,指向Function构造函数本身。
// 任何函数的constructor属性都指向Function function myFunction() {} console.log(myFunction.constructor === Function); // true // 箭头函数也是如此 const arrowFunc = () => {}; console.log(arrowFunc.constructor === Function); // true // 甚至内置方法的constructor也是Function console.log(Array.prototype.map.constructor === Function); // true
原型链关系:
// 所有函数都是Function的实例 function test() {} console.log(test instanceof Function); // true // Function自身的constructor指向自己 console.log(Function.constructor === Function); // true // 这是一个有趣的循环引用 console.log(Function instanceof Function); // true
总结关系:
eval - 执行代码字符串的工具函数
Function - 用于创建函数对象的构造函数
Function.prototype.constructor - 指向Function构造函数的引用,用于标识对象的构造函数