1

I saw this code while working on a project and am not sure what it does exactly. Someone please educates me. Thanks.

var f = new Function('return '+terms)($element);
return f($element);

The new Function()() looks to me like an Immediately-Invoked Function Expression and if it is it would return the value from 'return '+terms' expression, correct? Then why is f being called as a function in the return statement?

Updates:

  1. terms is an array containing just one element 'required', $element is a jQuery object of an HTML element
  2. Code execution never gets past the new Function() statement with the error message Uncaught ReferenceError: required is not defined. So inside new Function()() the function required() is invoked.
  3. I've never seen new Function()() syntax before. If it is an IIFE shouldn't it be written as (new Function(){})() instead?
Chris N
  • 17
  • 4

1 Answers1

2

Yes, you're correct that it's a invoked function - you can test it for yourself by doing:

var f = new Function("return 'a'")('b'); 
console.log(f);

'a'

The code you've posted can only work if terms is a string representing a function, meaning:

var f = new Function("return new Function('return arguments')")();
console.log(f, f(5));

function anonymous() { return arguments } [5]

Needless to say, it's rather peculiar way of writing JS.

Regarding the updates:

Actually what happens if terms = ['required'] is that this is transformed to a string by 'return '+terms, so you have new Function("return 'required'"). As this is a function that returns 'required' trying to invoke it as a function - required($elem) will give you indeed reference error. new Function("return required"). As this is a function that returns required, which isn't defined it will give you indeed reference error.

No, that's an acceptable way of writing it. More common is (new Function("[function body]"))() and in case of functions created without usage of Function object - (function(){})(). While new Function("[function body]")() will successfully run due to new operator precedence over () trying to run function(){}() will produce error.

eithed
  • 3,933
  • 6
  • 40
  • 60
  • 1
    Actually `'return '+terms` would wind up being `'return required'`. So, the `eval` fails since it can't find the variable `required`. – gen_Eric Jul 29 '14 at 20:07