当前位置: 首页 > news >正文

前端 JS 经典:动态执行 JS

前言:怎么将字符串当代码执行。有 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");

http://www.lryc.cn/news/369137.html

相关文章:

  • Laravel学习-模型注入
  • Django模板的使用(详细版)
  • 正则表达式基础
  • 【Linux】进程间通信之命名管道
  • 【内存管理】页表映射
  • Cloudpods 强大的多云管理平台部署
  • 深度学习的可微渲染
  • CAS Server Restful接口实现后台认证
  • Linux shell编程学习笔记58:cat /proc/mem 获取系统内存信息
  • 【InternLM实战营第二期笔记】07:OpenCompass :是骡子是马,拉出来溜溜
  • matlab演示银河系转动动画
  • 备战 清华大学 上机编程考试-冲刺前50%,倒数第5天
  • leetCode127. 单词接龙
  • 进程概念(二)
  • java程序100道01—20
  • 让GNSSRTK不再难【第二天-第7部分2】
  • 计算引擎:Flink核心概念
  • 技术前沿 |【大模型InstructBLIP进行指令微调】
  • CSS-布局-flex
  • 「C系列」C 数组
  • Python框架scrapy有什么天赋异禀
  • 【ROS2大白话】四、ROS2非常简单的传参方式
  • 浅谈mysql 的批量delete 和 使用in条件批量删除问题
  • 【Spring Boot】过滤敏感词的两种实现
  • 在 Zustand 中管理状态能使用类(Class)吗
  • MoreTable 方法selectWithFun,count 使用实例
  • 【SpringBoot】在Spring中使用自定义条件类在Java声明Bean时实现条件注入
  • 网卡聚合链路配置
  • PlantSimulation导入cad图作为背景
  • 【大模型】个人对大模型选择的见解