Executing eval ('({"ok": "true"})) returns {ok: "true"}. How does it work?

the following figure is obtained in Chrome:

clipboard.png

question:
first of all, str represents a json string, which should be no doubt . Then I run eval ("({"ok": "true"})) and return {ok: "true"} . How is this implemented? I went to see what I saw in the source code of a project written by someone else. I don"t know, so please let me know ~

May.28,2021

The

eval function takes a string and runs it as js code, returning the running result.

eval('({"ok":"true"})')

is equivalent to running

({"ok":"true"})

returns the object {ok: "true"} .

what I think I need to pay attention to is why do you add parentheses on both sides?
because {} can not only be used to declare objects, but also represent block-level scope,
if there are no parentheses on both sides, the {} will be parsed as a block-level scope, and a syntax error will be reported;
with parentheses, it will treat {} as an object declaration, so a new object will be generated and syntax errors will not be reported.


eval

avoiding using eval
eval () unnecessarily is a dangerous function, and the code it executes has the rights of the executor. If the string code you run with eval () is manipulated and modified by malicious parties (malicious people), you may end up running malicious code on the user's computer under the authority of your web page / extension. More importantly, third-party code can see the scope of an eval () when it is called, which can also lead to different attacks. Similar Function is not easy to attack.

eval () is usually slower than the alternative because it must call the JS interpreter, while many other structures are optimized by modern JS engines.

in common cases, we will find safer or faster solutions to replace eval ()


eval ()-imagine writing a piece of code for browser parsing with the same nature
such as let str ='x = {"ok": "true"}'; eval (str); creates an x variable in the current scope assigned to {ok:'true'}
your example eval ('('+ str +')'); < = = > is equivalent to writing a {ok:'true'}
directly in the browser. Because it is not a qualified expression, eval has parentheses on both sides

.
Menu