Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

different between eval(string) and eval(function)

I have web application which use the jsonp which return javascript codes to the client.

This is the code I return (to make it unreadable):

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

in the load function,we eval the codes.

However,we found that it is unreadable,but it is un-debuggeable.

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 insead of eval the code string,we will now eval a function object.

Is this possible?

Does they mean the same thing?

like image 812
hguser Avatar asked Nov 12 '22 19:11

hguser


1 Answers

You sure can. It'll be like simulating dynamic scoping in JavaScript. A few things to be aware of:

  1. You can't just directly eval a function. You need to convert it to a string. Use eval(String(f)).
  2. Give the function f a name. You can't do var g = eval(String(f)). Use the function name.
  3. Be careful. The function f will have access to all your local variables.

For example:

eval(String(getAdder()));

alert(add(2, 3));

function getAdder() {
    return function add(a, b) {
        return a + b;
    };
}

You can see the demo here: http://jsfiddle.net/5LXUf/

Just a thought - instead of evaluating the function object why not just call it? That'll give you your stack trace and it's much simpler and safer (the function won't have access to your local variables).

like image 132
Aadit M Shah Avatar answered Nov 15 '22 08:11

Aadit M Shah