The Dark Side is Eval.

    Date: 07/16/07 (Javascript Community)    Keywords: java

    I'm doing a brief essay on Design Patterns and JavaScript. It's specifically focusing on patterns explicitly for JavaScript (prototype related) or traditional patterns modified for JavaScript. One of my patterns, a take-off of the Decorator Pattern, is posing a problem.

    Essentially, I want my code to generate a new method at run-time that invokes another method. Something like this:

    
      function SpecialClass(methodToCall)
      {
        this.a = function() {methodToCall();}
      }
    
    This is horribly oversimplified. In reality, this.a will be doing something more like this: "go through a list of pre-call functions, call the 'methodToCall', then invoke a list of post-call functions".

    The issue here is that I don't know the interface of "methodToCall" until "a" is invoked. What I want to do is simply take the parameters as passed to "a" and forward them to "methodToCall". My current mechanism for that is done using the "eval" function. Essentially: "Convert the arguments array into a parameter string like so: 'arguments[0], arguments[1], arguments[2]...', build a string that reads: 'methodToCall(arguments[0], arguments[1]...)', and then pass that to eval.

    This... works. Mostly. There's a few glitches that are being caused by other parts of my code. What I'm really hoping to know is this- can I do this without calling "eval"? For debugging reasons and performance reasons, I'd like to avoid using eval. But due to design goals, I can't fix the interface of the methods- "a" has to be able to invoke any method, regardless of parameter list.

    If this can be done, I can track down the other problems in my code in minutes and finish my discussion on design patterns. If it can't, I need to start getting very creative about how I debug my code, since "eval"s and debuggers aren't the closest of friends. I'll still get my essay done, but it'll take longer. At any rate, if you want to read the essay, warts and all you'll see a more thorough discussion of the "AutoDecorator" pattern.

    Source: http://community.livejournal.com/javascript/136480.html

« Lightbox Solution || Code working in IE but not... »


antivirus | apache | asp | blogging | browser | bugtracking | cms | crm | css | database | ebay | ecommerce | google | hosting | html | java | jsp | linux | microsoft | mysql | offshore | offshoring | oscommerce | php | postgresql | programming | rss | security | seo | shopping | software | spam | spyware | sql | technology | templates | tracker | virus | web | xml | yahoo | home