JavaScript:在一个虚拟机中进行所有评估 [英] JavaScript: do all evaluations in one vm

查看:59
本文介绍了JavaScript:在一个虚拟机中进行所有评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个自定义JavaScript控制台,希望它可以像开发工具中的控制台一样工作.(或……类似REPL)

解决方案

您可以使用生成器函数,然后使用"feed"由于生成器保留其上下文,因此在评估下一行时,前几行中的所有变量都将存在:

  function * VM(expr){而(1){尝试 {expr = yield eval(expr ||'')} catch(err){expr =产量误差}}}vm = VM()vm.next()函数评价(行){让结果= vm.next(line).value如果(错误的结果instanceof)console.log(行,'错误',result.message)别的console.log(行,结果",结果)}评估('var a = 55')评估('a')评估('var b = 5')评估('c = a + b')评估('foobar--')评估('c ++')评估('[[a,b,c]') 

另一线程中所建议,自相似" eval 还将保留块作用域变量:

  let _EVAL = e =>eval(`_EVAL = $ {_ EVAL};未定义; $ {e}`)函数评价(行){尝试 {让结果= _EVAL(行)console.log(行,'==>',结果)} catch(err){console.log(line,'==>','ERROR',err.message)}}评估('var a = 55')评估('a')评估('foobar--')评估('让x = 10')评估('const y = 20')评估('[[a,x,y]') 

I'm creating a custom JavaScript console that I expect to work exactly like the console in dev tools. (or … something like a REPL) https://github.com/MohammadMD1383/js-interactive

I get user inputs one by one and evaluate them. eval(userInput)

the problem is with defining variables. I noticed that the eval function uses a new VM each time, so the declaration is in a separate VM than a call to the variable. so it causes the error someVarName is not defined

the sample of my code:

button.onclick = () => {
    evaluateMyExpression(textarea.value);
};

function evaluateMyExpression(code) {
    let result = eval(code);
    // do something else …
}

解决方案

You can use a generator function and "feed" expressions to it as they come in. Since the generator retains its context, all variables from previous lines will be there when you evaluate the next one:

function* VM(expr) {
    while (1) {
        try {
            expr = yield eval(expr || '')
        } catch(err) {
            expr = yield err
        }
    }
}


vm = VM()
vm.next()

function evaluate(line) {
    let result = vm.next(line).value
    if (result instanceof Error)
        console.log(line, 'ERROR', result.message)
    else
        console.log(line, 'result', result)
}

evaluate('var a = 55')
evaluate('a')
evaluate('var b = 5')
evaluate('c = a + b')
evaluate('foobar--')
evaluate('c++')
evaluate('[a, b, c]')

As suggested in another thread, a "self-similar" eval will also preserve block-scoping variables:

let _EVAL = e => eval(`_EVAL=${_EVAL}; undefined; ${e}`)

function evaluate(line) {
    try {
      let result = _EVAL(line)
      console.log(line, '==>', result)
    } catch (err) {
        console.log(line, '==>', 'ERROR', err.message)
    }
}

evaluate('var a = 55')
evaluate('a')
evaluate('foobar--')
evaluate('let x = 10')
evaluate('const y = 20')
evaluate('[a, x, y]')

这篇关于JavaScript:在一个虚拟机中进行所有评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆