Reputation: 36028
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?
Upvotes: 5
Views: 340
Reputation: 74204
You sure can. It'll be like simulating dynamic scoping in JavaScript. A few things to be aware of:
eval
a function. You need to convert it to a string. Use eval(String(f))
.f
a name. You can't do var g = eval(String(f))
. Use the function name.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).
Upvotes: 1
Reputation: 8049
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);
}
});
Upvotes: 0