views:

119

answers:

1

Trying hard to replace the eval without using Function constructor. Stumped. I am not a newbie but not an expert either.

jslint says this is evil; when I replaced it with a Function constructor, it said that was just a form of eval()!

   evaluateEventScript: function(requestObject) {
        var resultData;
        resultData = eval(requestObject.script);
        //send resultData elsewhere...
   }

Help??

+1  A: 

Can't you pass a closure in your scenario? e.g

var c = function(){
   ...
}


var evaluateEventScript = function(requestObject) {
    var resultData;
    resultData = requestObject();
    //send resultData elsewhere...
}

evaluateEventScript(c);

Or something in this form? this can work without eval or Function constructor. but it requires the requestObject to be a function object, and not a String.

If you get JSON as a result, than eval is your first bet, but there are alternatives:

http://www.ajaxonomy.com/2007/json/json-load-object-without-using-eval

Ehrann Mehdan
> "then eval is your first bet..." OK so sometimes it is OK to just ignore jslint's advice that eval is evil? Many websites go so far as to say "there is nearly ALWAYS a way to avoid eval, and you should" but then they do not explain how. Maybe it is time to invest in a good JS book rather than googling for answers. This forum is really cool though -- I am looking for questions I can answer as well, to give back.
Dave
I will check to see if I can use a closure here instead, as you suggest. I would still be interested in what the prescribed techniques are if I just want to replace the eval with the context I have supplied. Thanks in advance.
Dave