简体   繁体   中英

Is eval () dangerous in this Javascript code?

I found a similar question about the danger of eval() in the case below, but the answer didn't solve the problem and answered If it was dangerous or not, It only suggested another method. That is why I am asking again hoping to get a new answer. Also It was posted in 2016

So I want to pass a condition as a parameter, I know that this can be a function, but I've read that eval () is 67% faster than new function () {return...;} , that is why I am using eval ()

This is the code

 var a = [0]; function LoopWithDelay (func, delay, param, condition){ console.log(eval (condition)); if (eval (condition)) { func (param); setTimeout (LoopWithDelay, delay, func, delay, param, condition); } } function increment (x){ x[0] += 5; } LoopWithDelay (increment, 1000, a, "a[0]<10" );

When calling the LoopWithDelay() function I am passing the final parameter (condition) as a string so that It is evaluated inside the function eval (condition)

Is It wrong to use eval() in this case?

[edited]
My main focus is to make this code reusable and eliminate redundancy. That is why I want to pass the condition as a parameter.

Example:
In a test application where the screen flashes at different speeds depending on how much time is left.
If t = 0s flash every 2000ms
If 10s<t<20s flash every 1000s
etc.

It really looks like you are just trying to make a dynamic test that can react to something that changes in your code at runtime. You would typically do this by passing a function as a parameter, not a string with code to be later "eval()ed". This is the way you typically pass "behavior" or evaluate something that is only available at runtime. And it is very common in javascript. This has the same behavior, but doesn't need eval() :

 var a = [0]; function LoopWithDelay(func, delay, param, condition) { let condition_val = condition() console.log(condition_val); if (condition_val) { func(param); setTimeout(LoopWithDelay, delay, func, delay, param, condition); } } function increment(x) { x[0] += 5; } // capture `a` in the closure of the passed-in function LoopWithDelay(increment, 1000, a, () => a[0] < 10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM