eval5 static <code>version</code>static <code>global</code>static <code>eval</code>static <code>Function</code><code>constructor</code>(ct 介绍
eval5
基于 JavaScript 编写的 JavaScript 解释器
解决在不支持eval或Function的执行环境下执行 JavaScript 代码。例如:微信小程序
示例。
Usage
npm install --save eval5
import { evaluate, Function, vm, Interpreter } from "eval5"; // 设置默认作用域 Interpreter.global = window; //或 evaluate("1+1", Object.create(window)); evaluate("1+1", window); // 2 const func = new Function("a", "b", "return a+b;"); console.log(func(1, 1)); // 2 const interpreter = new Interpreter(ctx, { timeout: 1000, }); let result; try { result = interpreter.evaluate("1+1"); console.log(result); //2 } catch (e) { //.. }
Interpreter
static version
VERSION
static global
object 默认:Object.create(null)
设置默认作用域对象
例如:
Interpreter.global = window;
static eval
readonly
替代原有的eval占位符
如果执行环境支持 eval 函数建议使用原生的 eval,除非 eval 需要使用局部变量时,如下情况:
const ctx = Object.create(window); ctx.eval = Interpreter.eval; const interpreter = new Interpreter(ctx); interpreter.evaluate(` function test(){ var a = 1; return eval('a+1') } test(); `); // output 2
static Function
readonly
替代原有的Function占位符
作用同Interpreter.eval
除非不支持Function的环境,否则不建议使用
evaluate(code, { ... Function: Interpreter.Function })
constructor(ctx: {}, options?: { timeout?: number})
构造函数
var interpreter = new Interpreter(window);
evaluate(code: string, ctx?: {}): any
返回脚本中执行的最后一个表达式结果
var interpreter = new Interpreter(window); interpreter.evaluate("alert(1+1)");
setExecTimeout(timeout: number)
单位:ms
evaluate(code: string, ctx?: {})
执行给定的字符串脚本,返回脚本中执行的最后一个表达式结果
evaluate("console.log(1+1)", { console: console });
Function
同 js 原生的 Function
const func = new Function("a", "b", "return a+b;"); console.log(func(1, 2));
vm
参考 node.js vm
支持 api 列表:
- vm.createContext
- vm.compileFunction
- vm.runInContext
- vm.runInNewContext
- vm.Script
Support
- ECMA5
github仓库地址: https://github.com/bplok20010/eval5
在线示例: https://bplok20010.github.io/eval5/
在eval5解释器上运行echart4示例:
步骤一、复制 https://cdn.jsdelivr.net/npm/echarts@4.6.0/dist/echarts.min.js
代码,并粘贴到在线示例中运行。
步骤二、清除步骤一运行的代码,复制以下代码并运行:
root.style.height = '300px'; // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('root')); // 指定图表的配置项和数据 var option = { title: { text: 'ECharts 入门示例' }, tooltip: {}, legend: { data:['销量'] }, xAxis: { data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"] }, yAxis: {}, series: [{ name: '销量', type: 'bar', data: [5, 20, 36, 10, 10, 20] }] }; // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option);
效果示例:
eval5 static <code>version</code>static <code>global</code>static <code>eval</code>static <code>Function</code><code>constructor</code>(ct 官网
https://github.com/bplok20010/eval5
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。