Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error without new operator

I was reading this example on Promise. I realized that Error constructor is not called with new operator. Why does it work, then?

like image 839
hans-t Avatar asked Mar 09 '16 09:03

hans-t


People also ask

Can constructor be called without new?

No, this is not possible. Constructors that are created using the class keyword can only be constructed with new , if they are [[call]]ed without they always throw a TypeError 1 (and there's not even a way to detect this from the outside).

What is the use of new operator?

The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

What is new student () in JavaScript?

Summary: The new keyword is used in javascript to create a object from a constructor function. The new keyword has to be placed before the constructor function call and will do the following things: Creates a new object. Sets the prototype of this object to the constructor function's prototype property.

Why do we use new keyword in JavaScript?

New keyword in JavaScript is used to create an instance of an object that has a constructor function. On calling the constructor function with 'new' operator, the following actions are taken: A new empty object is created.


1 Answers

Because the specification says that the constructor function should check how it is called, and if it isn't called with new it should call itself with new and return that.

The Error constructor is the %Error% intrinsic object and the initial value of the Error property of the global object. When Error is called as a function rather than as a constructor, it creates and initializes a new Error object. Thus the function call Error(…) is equivalent to the object creation expression new Error(…) with the same arguments.

An example implementation of that in JS might look like:

function MyC(foo, bar) {
  if (!(this instanceof MyC)) {
    return new MyC(foo, bar);
  }
  this.foo = foo;
  this.bar = bar;
}
like image 162
Quentin Avatar answered Sep 22 '22 20:09

Quentin