javascript eval in context without using this keyword

后端 未结 4 1587
逝去的感伤
逝去的感伤 2021-01-14 00:54

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.

4条回答
  •  野的像风
    2021-01-14 01:12

    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);

提交回复
热议问题