I am writing a simple REPL implementation (Read, Evaluate, Print, Loop) in JavaScript. I can isolate the code and the calling context as follows:
var sandbox = { // Allow the input code to use predefined helper functions // without the preceding use of the this keyword. helper_fn: function() { alert("foo"); } }; var func = new Function("with (this) { " + user_inputed_code + " }"); func.call(sandbox);
Now it closes user_inputed_code , so this refers to the sandbox , and if the entered code accesses or mutates this , it affects the sandbox .
However, I noticed that if the imputed code should have accidentally forgot to precede the variable assignment with the
var keyword, the global namespace will be polluted.
Is there anyway to prevent this? If so, how (maybe a regular expression?)? Is there a better way to approach this?
source share