Create js function from string without eval and ne

2020-04-16 03:23发布

问题:

Is there any alternative solution to create js-function from string var, except eval() and Function constructor I'm not allowed to use this both methods for security reason.

I know solution when you create DOM element with js code and add to page, but it's absolutely dirty hack. Thank you very much for help.

====

ADD

I received json-data with string like "a === b", "!a", "(a && b) || c" and so on... (hundreds of combinations). Need to create and return function which can do this compare function.

Something

var test = function ('a === b') {
  //some code without eval and new Function()
}
// in console
test('aa', 'bb') // return false

回答1:

Thanks all of you for interesting answers.

So, I had read and tried to use all methods, that you suggested me. All of them it’s eval() even you wont be used eval in your code. In my project I fixed problem using WebWorkers. This technologi has a lot benefits, please read article in MDN https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers

But, I have to use "new Function" for this method.

So correct answer is:

You cannot create function from string without eval and new Function().

The only way it’s to write your own simple parser for that.

Thanks @brianxautumn