I am trying to execute eval within a particular context. I have found the answer here useful. However I am getting the following behavior in Chrome Version 53.0.2785.143 m.
This evaluates expressions in a given context without the need to prefix vars with 'this'.
Has caveats but works fine.
Can also incorporate custom functions in the expression.
Just call an 'evaluate' function, passing in your expression, context and an optional function.
The context must be a flat structure (no nested elements) and the function must be referred to as 'fn' inside the string expression. Answer prints 11 in this case:
var expression = "fn((a+b)*c,2)";
var context = { a: 1, b: 2, c: 3 };
var func = function(x,y){return x+y;};
function evaluate(ex, ctx, fn) {
return eval("var "+JSON.stringify(ctx).replace(/["{}]/gi, "").replace(/:/gi, "=")+", fn="+fn.toString()+";"+ex);
}
var answer = evaluate(expression, context, func);
console.log(answer);