javascriptiife

What is the purpose of "new Function()", especially as an IIFE?


I'm working a task to remove some JSHint warnings in our build. In particular, I'm getting rid of instances of "new Function()", because they're essentially eval statements.

I've run across a strange pattern in our code that I don't understand and am reluctant to change until I know what it does. Here's an example:

if(typeof(someObj.someProperty) === "string"){
someObj.someProperty = new Function("return " + someObj.someProperty + " ;")();
}

Neither I nor my coworkers can figure out what exactly this is supposed to accomplish. The best we can come up with is that it's some kind of attempt at cloning the property when it's a string. Nobody at all can figure out why it's declared as an IIFE.

Is this a pattern that anyone else has seen? If it is a clone, does it even matter for strings since they're immutable?


Solution

  • It looks like someone heard they shouldn't use eval, and decided to follow the letter of that advice but not the spirit. In other words, it is more or less equivalent to:

    if (typeof(someObj.someProperty) === "string") {
        someObj.someProperty = eval(someObj.someProperty);
    }
    

    To be precise, it is exactly equivalent to:

    if (typeof(someObj.someProperty) === "string") {
        someObj.someProperty = eval("(function () { return " + someObj.someProperty + "; })")();
    }
    

    This is still quite unsafe and all the caveats against eval apply equally well here.