Restricting eval() to a narrow scope

前端 未结 8 2154
误落风尘
误落风尘 2020-11-27 04:51

I have a javascript file that reads another file which may contain javascript fragments that need to be eval()-ed. The script fragments are supposed to conform to a strict s

8条回答
  •  一向
    一向 (楼主)
    2020-11-27 05:12

    Shog9♦'s Answer is great. But if your code is just an expression, the code will be executed and nothing will be returned. For expressions, use

    function evalInContext(context, js) {
    
      return eval('with(context) { ' + js + ' }');
    
    }
    

    Here is how to use it:

    var obj = {key: true};
    
    evalInContext(obj, 'key ? "YES" : "NO"');
    

    It will return "YES".

    If you are not sure if the code to be executed is expressions or statements, you can combine them:

    function evalInContext(context, js) {
    
      var value;
    
      try {
        // for expressions
        value = eval('with(context) { ' + js + ' }');
      } catch (e) {
        if (e instanceof SyntaxError) {
          try {
            // for statements
            value = (new Function('with(this) { ' + js + ' }')).call(context);
          } catch (e) {}
        }
      }
    
      return value;
    }
    

提交回复
热议问题