I would like to know , if the code below offers some insecurity to the site.
...
If yes, what is the safe way to write this code ?
You already know that the eval
causes the browser to interpret/execute a code in the same scope where it was called: so, "no". The code running next to the client is not able to modify the server, but has access to local declarations, since the global context anyone can quickly modify (now this is if you want to evaluate a string that came from elsewhere).
I’d worry about using eval
in this case, since it can shake the performance of a game (for example), both make the browser re-evaluate and execute a code.
The way you used the eval
it wasn’t very advantageous, like, you wanted to get a property from obj1
in a more customized way. Assignments also work with (exp)[expParaONomeDaPropriedade]
instead of (exp).identificador
:
obj1['0']; // o mesmo que obj1[0]
obj1['but1']; // o mesmo que obj1.but1
The difference of using the .
is because you are required to use an identifier in several ways currently:
({ 'a': 2 }).\u{61} // 2
({ 'a': 2 }).\u0061 // 2
({ 'B': 5 }).\u0042 // 5
({ 'B': 5 }).B // 5
Remembering that the name of all properties are forced to be strings, except a property with the name of type 'Symbol'...
Related: Eval is either good or bad?
– Guilherme Nascimento