This code works optimally and is easily comprehensible:
function evalInScope(js, contextAsScope) {
//# Return the results of the in-line anonymous function we .call with the passed context
return function() {
with(this) {
return eval(js);
};
}.call(contextAsScope);
}
evalInScope("a + b", {a: 1, b: 2}); // 3 obviously, but fails in strict mode!
However, the "smart" brains decided to remove the with statement without a proper replacement.
Question: how to make it work again in ES6, which is automatically in strict mode?
Don't use
eval, create anew Functioninstead. It won't inherit lexical strict mode - and even better, it won't inherit all your function-scoped and module-scoped variables:Also you don't get the weird "(last) statement result" return value that
evaluses, but can either confine thejscode to be an expression or include areturnstatement in the code itself.Alternatively, if you don't actually need to use a
withstatement with all its intricacies but just want to make a dynamic set of constant variables available to theevaled code, just generate the code for those constants dynamically. This allows toevalthe code in strict mode even:Or if the code doesn't use the
thiskeyword itself, maybe also