node.js - JavaScript Console -
i setup console in web browser using form fields. needs behave nodejs's repl (command line). in fact, using same api in both.
this falls-short because properties in context
available under this
. can please suggest tweak going? ideal if can keep context
unchanged, use object loop (via object.keys(context)` , set properties on nodejs' repl context.
var context = { debug: 'i debug' } function evalincontext(js) { return function() { return eval(js); }.call(context) } //this not need work, //confirms context under 'this' evalincontext('console.log(this.debug)') //prints 'i debug' //this needs work: try{ evalincontext('console.log(debug)') }catch(e){ //not good: referenceerror: debug not defined console.log(e) } evalincontext('var a=2') try{ evalincontext('console.log(a)') }catch(e){ //not good: referenceerror: not defined console.log(e) }
this in no way removes dangers of eval
, can create string object eval
s var
statement in function before eval
ing other piece of code.
in example below very important keys of variables
valid identifier names , note values turned json protect them tampering across invocations, if want functions etc you'll have implement them own way
var variables = { variables: undefined, // shadow self debug: 'foo' }; function evalwithvariables(code) { var key, variable_string = ''; (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
you may wish combine abstraction achieve own this
(as you're doing)
you may wish put definition inside iife returns custom eval function protect references variables
object, etc
Comments
Post a Comment