做网站容易 但运营难,新闻平台发布,百度小说风云榜,游戏公司网站模板下载前言#xff1a;怎么将字符串当代码执行。有 4 中方式实现 eval、setTimeout、创建 script 标签、new Function
1. eval
特点#xff1a;同步执行#xff0c;当前作用域
var name yq;
function exec(string) {var name yqcoder;eval(string);
…前言怎么将字符串当代码执行。有 4 中方式实现 eval、setTimeout、创建 script 标签、new Function
1. eval
特点同步执行当前作用域
var name yq;
function exec(string) {var name yqcoder;eval(string);
}
exec(console.log(name));
console.log(end); 2. setTimeout
setTimeout 的第一个参数可以传字符串的自动将这个字符串当作代码来运行
特点异步执行全局作用域
var name yq;
function exec(string) {var name yqcoder;setTimeout(string);
}
exec(console.log(name));
console.log(end); 3. 创建 script 元素
特点同步执行全局作用域
var name yq;
function exec(string) {var name yqcoder;const script document.createElement(script);script.text string;document.head.appendChild(script);
}
exec(console.log(name));
console.log(end); 4. 使用 Function
特点同步执行全局作用域
var name yq;
function exec(string) {var name yqcoder;new Function(string)();
}
exec(console.log(name));
console.log(end);