Function和eval都可以执行javascript代码片段,假设,需要在window环境中执行如下代码:
1.Function
// 假设当前执行环境是this,即window;
let content = this;
let executeCode = function (str) {
return new Function(str);
}
首先创建当前环境content,然后通过函数表达式创建可执行实例
- 案例1: 获取当前的href
// 创建可执行的字符串consoleStr
let consoleStr = `console.log(window.location.href)`;
// 创建可执行的函数引用
let consoleRender = executeCode.call(content, consoleStr);
// 执行
consoleRender();
- 案例2: 在某个节点中插入新创建的div
<body>
// 全文根节点
<div id="app"></div>
<script>
// 创建可执行的字符串nodeStr
var nodeStr = `var node = document.createElement('div');
node.innerHTML = 'hello world';
document.querySelector('#app').appendChild(node);`
// 创建可执行的函数引用
let nodeRender = executeCode.call(content, nodeStr);
// 执行
nodeRender();
</script>
</body>
2.eval
eval直接可以通过如下方式执行:
eval(consoleStr);
eval(nodeStr);
总结:Function和eval在执行代码片段方便能达到同样的效果,但是出于安全问题,推荐使用Function。