Function with eval won't make it through minif

2019-08-30 14:01发布

问题:

Here is my weird function that let my users create their own javascript code

function evalThisFunction(functionBody){        
     var func;
     eval("func = " + functionBody);
     return func;
}

But after minification with Closure Compiler (http://closure-compiler.appspot.com/), I get this result :

function a(b){eval("func = "+b);}

Do you see a way I can modify my weird function so it will still works after minification?

回答1:

Yes, use the Function constructor:

function evalThisFunction(functionBody){        
     return Function(functionBody);
}

Alternatively, you can swap out the above code entirely for Function , it seems to do what you want anyway. eval has scoping issues.