【发布时间】: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)
}
【问题讨论】:
-
仅供参考:您的浏览器中已经有一个控制台,在 devTools 中:))
标签: javascript node.js