1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Workarounds for JavaScript "eval"

Discussion in 'JavaScript and AJAX' started by pradeep, Sep 17, 2008.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:

    Introduction


    One Javascript function that gets used such frequently than it should to be is "eval". "eval" evaluates the content of a text string passed to it and then executes it as if it were normal Javascript code..

    Actually, we should never use eval for any purpose in our code, be it dynamic variable access, or dynamic code execute or the likes there is always a workaround. "eval" is usually used by beginners and amateurs most of the times to access some dynamic variable i.e. in a situation where a variable is a part of another varibale name. Example: You have variable str1,str2...strn, so to access them you may write:

    Code:
     var myStr = eval('str'+i); // where i is our counter variable
     

    Solution to Dynamic Variable Access



    For those who don't know all global variables are held in the window object, so we can bypass "eval" to access the require variable like this:

    Code:
     var myStr = window['str'+i]; // where i is our counter variable
     
    This much better, faster and safer way to access a dynamic varibale.

    Dynamic Code Execution



    Sometimes some experienced programmers may still use eval, of course for something quite complicated than accessing a dynamic variable. There also we can avoid using eval, by creating a function with the code to execute and then calling the function. Normally we would do this.

    Code:
     var myCode = 'alert("Howdy?");';
     eval(myCode);
     
    Now let's try the non-eval approach,

    Code:
     var myCode = 'alert("Howdy?");';
     var myFucn = new Function(myCode);
     myFucn();
     
    The alternative method may produce code a bit longer than the eval one, but the later one is better and easier to understand, and it should also run faster.
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,292
    Likes Received:
    365
    Trophy Points:
    83
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,292
    Likes Received:
    365
    Trophy Points:
    83
  4. amitvjog

    amitvjog New Member

    Joined:
    Dec 3, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi,
    Can you please explain the reasons behind not using 'eval', or just that beginners are using it we should not use it?

    Regards,
    Amit Jog
     
  5. vol7ron

    vol7ron New Member

    Joined:
    Dec 3, 2008
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    I know this may not be a debugging forum, but I'm trying to get something similar to work. Notice the "
    function (replace){}" at the bottom. Do you know of any way to add an event to run code stored in a variable?

    So given the below, I want getObjById('outputID').innerHTML='hello';
    to run when the first link is clicked. Thank you for any help/explanations that can be shed on this subject.

    attachEventHandlers(obj, eventType, fn, useCapture){
    if (obj.addEventListener) {
    obj.addEventListener(eventType, fn, useCapture);
    return true;
    } else if (obj.attachEvent) {
    var val = obj.attachEvent("on"+eventType, fn);
    return val;
    } else {
    try {
    obj.eval("on" + eventType) = fn;
    } catch (err) {
    return;
    }
    }
    }
    function init(){
    replace = "getObjById('outputID').innerHTML='hello';";
    attachEventHandlers(document.links[0]
    , 'click'
    , function (replace){}
    , false
    );
    }
     
  6. vol7ron

    vol7ron New Member

    Joined:
    Dec 3, 2008
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    I found that the following will work:
    Code:
    function init(){
       replace = "getObjById('outputID').innerHTML='hello';";
       replace = new Function(replace);
       attachEventHandlers(document.links[0]
          , 'click'
          , replace
       , false
       );
    }
    I'm just not sure I understand why I couldn't use new Function(replace) or function(replace) instead...hmm

    Thanks for the article, regardless.
     
  7. vol7ron

    vol7ron New Member

    Joined:
    Dec 3, 2008
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Nevermind, using new Function(replace), instead of function(replace){} worked! thank you for the article! I've done this before, just have forgot after all this time and didn't feel like going through old code.

    Amit,
    My example should be a good reason of when not to use eval. I think eval executes at runtime, or, at the least it is quirky. When trying to late-bind an event, eval() did not do what I wanted it to do. It ran the code at page load, rather than when the event was triggered. Instead, using the new Function() did exactly what needed to be done when late-binding an event.

    This is just my example, I'm sure there are other pros/cons though.

    Hope that helps,
    vol7ron
     
  8. gkumar

    gkumar New Member

    Joined:
    Jun 16, 2009
    Messages:
    58
    Likes Received:
    5
    Trophy Points:
    0
    You will have to write an eval yourself. You will have to parse the string and invoke the right operators.
    Here's a link to get you started.
    The Tamarin project has a ECMAScript parser written in ES4. Try this as well.
    "You can even write the entire javascript inside as3, so that you do not need to touch the actual html page." Do you have links / tutorials? – okoman
    Both AS and JS are based on the same ECMAScript standard. So, if you pass a string of AS3 to a container, and use JS's eval on this string, it should work just fine.
     
  9. David Michael

    David Michael New Member

    Joined:
    Jul 6, 2009
    Messages:
    10
    Likes Received:
    0
    Trophy Points:
    0
    I think they use it...try to read the whole code.
     
  10. elizas

    elizas New Member

    Joined:
    Feb 9, 2010
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    Hi,
    i would like to add to this.
    In JavaScript replace function is basically used to replace some string in an another string. In replace function you can see that we are passing the regular expression to replace, but if the data is dynamic and i want to replace it in runtime .The over all concept is that in replace function of JavaScript we can not pass a variable to replace, we have to pass a regular expression - if we want to use a variable to replace we have to convert it to regularexpression.

    thanks
    Eliza
     
  11. Full Zip Hoody

    Full Zip Hoody New Member

    Joined:
    Sep 29, 2010
    Messages:
    20
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Programer
    Location:
    US of A
    "we should never use eval for any purpose in our code, be it dynamic variable access, or dynamic code execute or the likes there is always a workaround" true
     

Share This Page