Skip to content

代码求值 ​

JS 能在运行时动态地解释并执行字符串代码,代码求值方式包括:

  • eval()
  • Function
  • 定时器
  • <script>

eval() ​

eval() 将传入的字符串作为 JS 代码执行,返回最后一个表达式的执行结果,如果传入的是非字符串,则直接返回该值。

Function ​

Function 构造函数前面参数作为形参,最后一个参数作为函数体。

使用 Function 创建的函数,不会产生闭包。

js
function a() {
  const n = 100
  return new Function('console.log(n)')
}
const b = a()
b() // ReferenceError: a is not defined

定时器 ​

setTimeout() 和 setInterval() 可解析字符串

js
setTimeout('console("Hi")', 100)

<script> ​

<script> 标签的 text 属性可接收字符串。

js
const script = document.createElement('script')

script.text = `
function a() {
  console.log('Hi')
}
a()
`
document.body.appendChild(script)