6

I am using eval function in a weird way, as a constructor.

try {
  var y = new eval()
} catch(error) {
    console.log("caught a " + error.name + ": " + error.message);
}

It throws error as,

caught a TypeError: function eval() { [native code] } is not a constructor

As the error message shows, eval is a function but not a constructor.

The question is, don't all javascript functions act as constructors as well?

Noah Freitas
  • 17,240
  • 10
  • 50
  • 67
  • eval is a reserved keyword / a native function. Dont mess with it. – Pierre Gayvallet Dec 04 '15 at 16:03
  • 2
    No, some other notible exceptions are some _DOM_ methods and _arrow functions_ `x => undefined` – Paul S. Dec 04 '15 at 16:04
  • Agreed, eval is a built-in function. If you made your own `function myEval() {}` and then used that code it should be fine. – jmbmage Dec 04 '15 at 16:04
  • You may refer to [this](http://stackoverflow.com/questions/22401553/what-are-all-the-difference-between-function-and-constructor-function-in-javascr) for better understanding between the difference. – marukobotto Dec 04 '15 at 16:09

1 Answers1

6

Not all functions are constructors.

Constructors are function values with a [[Construct]] internal property, which not all functions have. This is made explicit in 6.1.7.2 Object Internal Methods and Internal Slots of the language spec:

A function object is not necessarily a constructor and such non-constructor function objects do not have a [[Construct]] internal method.

Using new or Reflect.construct to call a non-constructor as a constructor throws a TypeError.

Noah Freitas
  • 17,240
  • 10
  • 50
  • 67
  • What are the practical implications of this? If I write a javascript function, is it automatically tagged with this [[Construct]] internal method? – Frank Bryce Dec 04 '15 at 16:34
  • @JohnCarpenter, it depends on how the function is created. As @PaulS points out above, creating a function using the arrow function syntax means it will not have the [[Construct]] property. Using the `function` keyword will generally produce a construct-able function. – Noah Freitas Dec 04 '15 at 16:44
  • Huh, add this to the list of things that I didn't know that I didn't know. – Frank Bryce Dec 04 '15 at 16:49