calling eval() in particular context

前端 未结 14 1123
说谎
说谎 2020-11-27 17:05

I have following javaScript \"class\":

A = (function() {
   a = function() { eval(...) };
   A.prototype.b = function(arg1, arg2) { /* do something... */};
}         


        
14条回答
  •  忘掉有多难
    2020-11-27 18:02

    Folks, I think that I have the definitive answer. It works on both JavaScript (Browsers) and NodeJs.

    function evalInContext(Context,toEval){
      return eval(`(function Main(){${toEval}})`).call(Context);
    }
    
    var context = {a:42,b:82,c:103};
    var toEval = "return this";
    
    console.log(evalInContext(context,toEval));//{"a": 42, "b": 82, "c": 103}

    Tested on Node v12.16.1, Node v14.7.0, Firefox v79.0 and Google Chrome v84.0.4147.105

提交回复
热议问题