user2879704
user2879704

Reputation:

Aren't all JavaScript functions constructors as well?

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?

Upvotes: 6

Views: 119

Answers (1)

Noah Freitas
Noah Freitas

Reputation: 17430

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.

Upvotes: 7

Related Questions