Different between eval (string) and eval (function)

I have a web application that uses jsonp which return javascript codes to a client.

This is the code I'm returning (to make it unreadable):

 com.xx.load('xx','var name="hguser";function data(x){console.info(x); }') 

in the load function, we are eval codes.

However, we found that it is not readable, but it is not being debugged.

So I wonder if we can use this:

 com.xx.load('xx',function(){ var name='hguser'; function data(x){ console.info(x); } }); 

Then in the load function inside the line of the eval line of code, now we will be the eval object of the function.

Is it possible?

Does this mean the same thing?

+4
source share
2 answers

Are you sure you can. It will look like a simulation of dynamic reach in JavaScript. A few things to know about:

  • You cannot directly use the eval function. You need to convert it to a string. Use eval(String(f)) .
  • Give the function f name. You cannot do var g = eval(String(f)) . Use the function name.
  • Be careful. Function f will have access to all your local variables.

For instance:

 eval(String(getAdder())); alert(add(2, 3)); function getAdder() { return function add(a, b) { return a + b; }; } 

Here you can see the demo: http://jsfiddle.net/5LXUf/

Just a thought - instead of evaluating an object of a function, why not just name it? This will give you a stack trace, and it is much simpler and safer (the function will not have access to your local variables).

+1
source

check the following simplified code : as I said in the comment, the second approach will not work, because it returns the result of the function,

 var my_load=function(arg1,for_eval) { eval(for_eval);  data(1); } my_load('xx','var name="hguser";function data(x){console.info(x); }'); my_load('xx',function(){  var name='hguser';  function data(x){   console.info(x);  } });โ€‹ 
0
source

Source: https://habr.com/ru/post/1441176/


All Articles