问题
I know this may be a newbie question, but I'm curious as to the main benefit of eval()
- where would it be used best? I appreciate any info.
回答1:
The eval
function is best used: Never.
It's purpose is to evaluate a string as a Javascript expression. Example:
eval('x = 42');
It has been used a lot before, because a lot of people didn't know how to write the proper code for what they wanted to do. For example when using a dynamic name for a field:
eval('document.frm.'+frmName).value = text;
The proper way to do that would be:
document.frm[frmName].value = text;
As the eval
method executes the string as code, every time that it is used is a potential opening for someone to inject harmful code in the page. See cross-site scripting.
There are a few legitimate uses for the eval
function. It's however not likely that you will ever be in a situation where you actually will need it.
回答2:
This is quite an old question, and perhaps people didn't think of use cases for eval()
properly at the time. One great use for eval()
is for implementing hot reloading into your backend or frontend development flow.
Basically eval()
can make it possible for you to edit code in your editor, and have it patch your running application without it restarting, and without it losing state (depending on the implementation). You will need associated code that watches for file changes, and somehow sends the changes to your application, but eval()
is ultimately the method of converting those changes into actual js.
EDIT
Another use case I have come across:
You can use eval()
to bypass webpack's compilation process in events where you want to dynamically require files that you don't want to be transpiled (like json) For example:
const data = eval('require')(`./emails/${recipient}/${type}.json`)
On that note, I think it is entirely wrong to write a statement like eval()
is evil, or should never be used. Blanket statements like these are the real evil!
回答3:
eval
makes it possible to execute (or evaluate) a string of javascript code.
Thus, it is applicable when you want someone to execute a string of javascript code. Like, for example, under an educational article about JavaScript, so the reader can immediately try it :)
Or, again if your website is targeted to programmers, you may want them to write and execute their own plugins.
回答4:
eval()
should not be used in Javascript.
eval()
used to be used to parse JSON strings, but that use has been superseded by the faster and more-secure JSON.parse
.
回答5:
The best goal of using eval is to dynamically load code, generate code at runtime and do similar meta programming stuff. In general, if you can do the same without eval, don't use eval.
回答6:
eval() = evil
You should not really use it at all. It can be used for easy code insert, but someone can insert bad scripts using eval()
. Sometimes people use eval()
for parsing JSON, or
eval("obj." + id); //newbies
but actually you can achieve all those things without using eval()
.
obj[id]; //should-do
回答7:
You can run JS that is stored in the value of a field on the webpage.
You can use eval with JS, it's just that then your code is more viable to attack. As long as it doesn't use AJAX, there's no server problem.
If you use eval, you should parse out the characters [ ()<>{} ]
回答8:
As said earlier, there is a potential risk involved while using eval(), If you want to evaluate string as expression you can use ${} to evalute expression, introduced in ECMA-6
回答9:
one of the best use case using eval is javascript logger in which user can execute javascript in run time. for example javascript logger allowing the user to execute script in logger window.
回答10:
To dynamically run code based on strings that represent javascript code. e.g:
let dynamicFunc = eval('(x)=>(x+2)') // or whatever plain text which is valid JS function
console.log(dynamicFunc(40));
// expected output: 42
Security warning! you should always validate these strings to avoid malicious scripts execution, especially when using it on the server side.
回答11:
Maybe I am wrong, but I am using it to parse a string from a templete file:
const name = 'Daman'
const fileContent = 'Hello ${name}'
const result = eval('`' + fileContent + '`')
Which gives me just what I need:
"Hello Daman"
回答12:
you could build a client skeleton and have it work as a foundation app - receiving bundles of code and then executing them - thereby making the client extremely flexible -- having all code on server in bundles. This however is highly risky and if such a thing is needed, then you should perhaps use Java with Java bundles. Why Eval is still in the language is debateable, it is a too big security risk to use
回答13:
Using eval is usefull, but like everything else, you must be aware of the risks. Every pice of JS code is a potential risk. Bugs in software creep in through logical errors and coding errors witht unintended consequences. I always say that computers never do what you want them to do, they do what you tell them to do. That means you must remember that software has to be carefully thought out. Software hasn't changed. People still code on-the-fly instead of careful analasys and proper design. We are all guilty of the same sins in software development. Use eval - eval is not evil, it is what you make it.
回答14:
Never say never. Eval has very good legitimate use cases. It's just a powerful tool, so if you aren't conscientious of how you're using it you could create a serious problem.
Since Javascript is executed client side, the security risk is to the client rather than the server. If you use eval in javascript and you aren't careful to validate the source of input or the content of that input to the eval function, you'd be responsible for potentially serious consequences for the client.
Having said that, the best use I've made of javascript eval is when writing various types of parsing routines. It's often handy to put simple (or sometimes not-so-simple) math formulas into data as a string that's stored in a database for example. If your program needs to perform arbitrary calculations on variables that are otherwise controlled by the program, eval is the best way to do that. It can be unnecessarily complex manually parse a securely managed string.
As developers we can't fully control what happens client side. A user can always muck about in the console and create their own problems, or download browser extensions that interfere with JS execution. The best we can do is to limit risk exposure, and not be so negligent as to leave gaping security holes.
回答15:
Eval()
can be very useful, even though it was said to be "undone". I use it in autoit
to enable code upon code.
It can be applied when writing a code-processor to create your own script.
WHY? In my case using this on a large scale tcp server doesn't require me to recompile source code and kick all clients cause of restarting. So I use eval to add in new scripts on the fly unlike a config stuff it isn't static and can be used to calculate etc. Also combining eval with call commands can set a value by eval from a function.
But beside that, it won't be much safe to use. Even using it this way I recommend making it fail safe for sure.
来源:https://stackoverflow.com/questions/10474306/whats-the-main-benefit-of-using-eval-in-javascript