Es6 class constructors cannot be invoked without new
A great topic!
In ECMAScript 6 (ES6), class constructors are designed to be invoked only with the new
keyword. This is a deliberate design choice to ensure that classes behave like constructors, which is a fundamental concept in object-oriented programming.
When you define a class constructor in ES6, it is not a regular function that can be called without new
. Instead, it is a special kind of function that is designed to create and initialize objects.
Here's an example:
class MyClass {
constructor(name) {
this.name = name;
}
}
If you try to invoke the constructor without new
, you'll get a TypeError
:
const obj = MyClass('John'); // TypeError: MyClass is not a constructor
This is because the MyClass
constructor is not a regular function that can be called without new
. Instead, it is a class constructor that is designed to be used with new
.
When you use new
to invoke the constructor, it creates a new object and calls the constructor to initialize it:
const obj = new MyClass('John'); // creates a new object and initializes it
console.log(obj.name); // outputs "John"
By requiring new
to invoke the constructor, ES6 classes ensure that objects are created and initialized correctly, which is essential for maintaining the integrity of the object-oriented programming model.
It's worth noting that this behavior is not unique to ES6 classes. In fact, this is a common pattern in many programming languages, including Java, C#, and others.