5

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?

hguser
  • 35,079
  • 54
  • 159
  • 293
  • 1
    In this case I think you can use `new Function('var name="hguser";function data(x){console.info(x); }')` instead of `eval` – elclanrs Oct 22 '12 at 02:51
  • +1,don't know why yo got downvoted. – gdoron Oct 22 '12 at 02:54
  • we use `eval` instead of `new Function` because the returned codes will access some `variables defined in my page`. But I wonder if you mean this:`(new Function('.....'))();`? Since the `eval` will execute the code at once. – hguser Oct 22 '12 at 02:55
  • in second approach you will eval the function result, not the function, result is *undefined* – zb' Oct 22 '12 at 03:50

2 Answers2

1

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).

Community
  • 1
  • 1
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
  • in fact what we want is what you said:the stack trace. since we can not get the trace if we use`eval(string)` in the returned `jsonp` – hguser Oct 22 '12 at 06:07
  • @hguser - The above code will give you a correct stack trace. See the demo (open your debugger): http://jsfiddle.net/5LXUf/1/ – Aadit M Shah Oct 22 '12 at 09:57
0

check the following simplified code: as i said in comment, 2nd approach will not work, because it return function result,

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); 
  }
});​
zb'
  • 8,071
  • 4
  • 41
  • 68