2

在 JavaScript 中使用eval. 我得到了这个(使用 jQuery 终端):

term = $('#term_demo').terminal(function(command, term) {
    if (command !== '') {
        var result = window.eval("(" + command + ")");
        if (result !== undefined) {
            term.echo(String(result));
        }
    } else {
       term.echo('');
    }
}, {
    greetings: 'Javascript Interpreter',
    name: 'js_demo',
    height: 200,
    prompt: 'js> '
});

演示

function foo() { ... }但是当我执行foo未定义我需要使用时它不起作用foo = function() { ... }。eval 就像在(function() { <code> })(). 是否有更复杂的代码也不起作用?

是否可以在不使用js.js的情况下使用简单代码创建一个 JavaScript 解释器,它与浏览器控制台的工作方式相同?

4

2 回答 2

2

我创建了一个书签,它在页面中附加了一种 REPL,专为主要的五种浏览器(Chrome 1+、IE 6+、Firefox 1+、Safari 3+、Opera 9+不记得确切的版本)而设计.
评估代码的核心组件发布在下面,稍作修改+注释。

/**
 * Evaluates some code in the global scope.
 * @param String code: Code to eval
 * @return Stringified result, prefixed with 'E:' if error.
 */
function globalEval(/*string*/ code) {
    var win = window, r, raw;
    try {
        if (win.execScript) { // eval in IE sucks, so use execScript instead
            r = win.$_$_$globalEval$_$_$ = {c:code};
            win.execScript('try{$_$_$globalEval$_$_$.r=eval($_$_$globalEval$_$_$.c);}catch(e){$_$_$globalEval$_$_$.e=e}');
            // /*Optional clean-up:*/ delete win.$_$_$globalEval$_$_$;
            if (r.e) throw r.e; // Error
            raw = r.r;
        } else {
            raw = win.eval(code);
        }
        r = '' + raw; // Stringify in the try-block
                      // It is possible that an error is thrown
                      // for example, for the following code: ({toString:1})
    } catch(err) {
        r = (err + ''); // Convert error to string
        // IE: If found, "[object" will be at index zero, which is falsy
        if (!r.indexOf('[object')) r = err.message;
        // r = 
        r = 'E:' + (raw=r);
    } finally {
        // raw = unmodified result (or Error instance)
        // FOR THIS EXAMPLE, raw is not used, and string r is returned
        return /*string*/ r;
    }
}

我已经在一个表单中实现了该功能,其中包含几个控件,包括一个输入+输出文本区域。

Note: The code is evaluated in the global context. And such, any variables in code will be leaked to the global scope. For an interpreter, you could use an iframe to create a new scope (and modify var win in my function).

var win = frames['name_of_frame'], ... // or
var win = frame_DOM_element.contentWindow, ...
于 2012-06-24T13:19:24.783 回答
0

您在传入命令周围附加的括号会产生非法语法。你应该用一个匿名的自执行函数来包装它。

示例:http: //jsfiddle.net/bW6Fv/1/

var command = "function foo(x){return x+x;} alert(foo(10));";

window.eval("!function(){" + command + "}()");​

编辑

如果您希望您的评估脚本在全球范围内可用,您必须将它们展开或显式地将值分配给全局窗口对象。

示例:http: //jsfiddle.net/bW6Fv/2/

var command = "window.foo = function(x){return x+x;}; alert(foo(10));";

window.eval("!function(){ " + command + "}();");
window.eval("alert(foo(20));");

command = "function bar(x){return x / 2;}; alert(bar(10));";

window.eval(command);
window.eval("alert(bar(20));");
于 2012-06-24T13:16:12.933 回答