【问题标题】:JavaScript ConsoleJavaScript 控制台
【发布时间】:2015-07-08 08:09:09
【问题描述】:

我想使用表单字段在 Web 浏览器中设置控制台。它需要表现得更像 nodejs 的 repl(命令行)。事实上,我将在两者中使用相同的 API。

这是不足的,因为context 中的属性仅在this 下可用。你能建议一个调整来实现这个吗?如果我可以保持context 不变,那是理想的,我使用这个对象循环(通过 Object.keys(context)` 并在 nodejs 的 repl 上下文中设置属性。

var context = {
    debug: 'I am debug'
}

function evalInContext(js) {
    return function() { return eval(js); }.call(context)
}

//This does not need to work, but it 
//confirms that the context is under 'this'
evalInContext('console.log(this.debug)') //prints 'I am debug'

//This really needs to work:

try{
    evalInContext('console.log(debug)') 
}catch(e){
    //not good: ReferenceError: debug is not defined
    console.log(e)
}

evalInContext('var a=2')
try{
    evalInContext('console.log(a)') 
}catch(e){
    //not good: ReferenceError: a is not defined
    console.log(e)
}

http://jsfiddle.net/hy8hewq4/

【问题讨论】:

  • 仅供参考:您的浏览器中已经有一个控制台,在 devTools 中:))

标签: javascript node.js


【解决方案1】:

这绝不会消除eval 的危险,但是您可以从一个Object 创建一些String,其中evals 作为var 声明在evaling 另一段代码之前,您在 function 中执行此操作。

在下面的示例中,非常重要 variables 的键是有效的标识符名称,并注意将值转换为 JSON 以防止它们被篡改调用,如果你想要函数等,你必须以自己的方式实现它们

var variables = {
    variables: undefined, // shadow self
    debug: 'foo'
};

function evalWithVariables(code) {
    var key, variable_string = '';
    for (key in variables) {
        variable_string += ', ' + key + ' = ' + JSON.stringify(variables[key]);
    }
    if (variable_string.length) eval('var' + variable_string.slice(1));
    return eval(code);
}

evalWithVariables('console.log(debug)'); // logs foo

您可能希望将其与另一个抽象结合以实现您自己的this(就像您目前所做的那样)

您可能还希望将此定义放在一个 IIFE 中,它只返回您的自定义 eval 函数以保护对您的 variables Object 等的引用

【讨论】:

  • 这使得所有变量都可用:function evalInContext(js) { with(context) {eval(js)} } ... 但是它没有保留a 变量。
  • 您无法访问作用域链以查看已更改的内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 2016-08-18
  • 1970-01-01
  • 1970-01-01
  • 2013-04-16
  • 2018-01-31
  • 2014-10-20
相关资源
最近更新 更多