calling eval() in particular context

前端 未结 14 1122
说谎
说谎 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 17:47

    I was struggling with this for a while in Angular, and found this answer the most useful. I was trying to implement some existing code which use 'with', not allowed by strict. My 'knife and fork' solution to not having to use 'this.' inside the expression I wanted to evaluate, and avoiding 'with' and 'eval' was:

    let evalInContext = function (js, context) {
        let keys = Object.keys(context);
        //let code = 'function it(){';
        let code = '';
        for (let i = 0; i < keys.length; i++){
            code += 'let '+keys[i]+' = window._evalincontextobj.'+keys[i]+';\n';
        }
        code += 'return (';
        code += js;
        code += ')';//}\n return it();';
        window['_evalincontextobj'] = context;
        let res = Function(code)();
        console.log(js+' = '+res);
        delete window['_evalincontextobj'];
        return res;
    }
    

    This is working for expressions like (watched === 'hello') where 'watched' is a member of context.

提交回复
热议问题