Legitimate uses of the Function constructor

NWMatcher — Javascript CSS selector and matcher, by Diego Perini — uses Function constructor (1, 2, 3, 4, etc.) to create (“compile”) highly-efficient versions of selector matchers.

The benchmark (which I just ran on Chrome 5) speaks for itself:

alt text

Note the difference between NWMatcher and Sizzle, which is a very similar selector engine, only without function compilation 🙂

On a side note, ECMAScript 5 doesn’t throw any errors on invocation of Function. Neither in strict, nor in “standard” modes. Strict mode, however, introduces few restrictions on presence of identifiers such as “eval” and “arguments”:

  • You can’t have declare variables/functions/arguments with such names:

    function eval() { }
    var eval = { };
    function f(eval) { } 
    var o = { set f(eval){ } };
    
  • You can’t assign to such identifier:

    eval = { };
    

Also note that in strict mode, eval semantics is slightly different from that in ES3. Strict mode code can not instantiate variables or functions in the environment from which it was called:

 eval(' "use strict"; var x = 1; ');
 typeof x; // "undefined"

Leave a Comment