I was reading this example on Promise
. I realized that Error
constructor is not called with new
operator. Why does it work, then?
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).
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With