pojin (ID: 1)
头衔:论坛坛主
等级:究级天王[荣誉]
积分:414
发帖:45 篇
来自:保密
注册:2022-05-03 21:53:24
造访:2022-11-17 08:42:05
发帖:45 篇
来自:保密
注册:2022-05-03 21:53:24
造访:2022-11-17 08:42:05
[ 第 1 楼 ]
回复

一、简介
eval 和 new Function 都可以将一段字符串解析成一段js脚本并执行。
二、使用
1、eval
作为一个全局方法,传入一个参数(String)即可执行
let name = 'a'
eval('console.log(name)')
// 输出'a'
2、new Function
new Function() 可以接n个参数,最后一个参数作为函数体。
let name = 'a'
let test = new Function('arg', 'console.log(arg)')
//等同于 test = function(arg) { console.log(arg)}
test(name)
// 输出'a'
三、eval和 new Function的区别
eval的代码执行时的作用域为当前作用域,它可以访问函数中的局部变量。
new Function中的代码执行时的作用域为全局作用域。
let name = 'a'
function test() {
let name = 'b'
eval('console.log(name)') // 'b'
let fn = new Function('console.log(name)') //'a'
fn()
}
test()
四、为什么不建议使用eval
因为它可以执行传给它的任何字符串,所以永远不要传入来历不明和不受信任源的字符串。
eval 和 new Function 都可以将一段字符串解析成一段js脚本并执行。
二、使用
1、eval
作为一个全局方法,传入一个参数(String)即可执行
let name = 'a'
eval('console.log(name)')
// 输出'a'
2、new Function
new Function() 可以接n个参数,最后一个参数作为函数体。
let name = 'a'
let test = new Function('arg', 'console.log(arg)')
//等同于 test = function(arg) { console.log(arg)}
test(name)
// 输出'a'
三、eval和 new Function的区别
eval的代码执行时的作用域为当前作用域,它可以访问函数中的局部变量。
new Function中的代码执行时的作用域为全局作用域。
let name = 'a'
function test() {
let name = 'b'
eval('console.log(name)') // 'b'
let fn = new Function('console.log(name)') //'a'
fn()
}
test()
四、为什么不建议使用eval
因为它可以执行传给它的任何字符串,所以永远不要传入来历不明和不受信任源的字符串。

