In ES6, classes are syntactic sugar for constructor functions. When a class is invoked without the new keyword, it does not create a new instance of the class. Instead, it calls the class's constructor function directly.
Consider the following class:
class Foo {
constructor(x) {
if (!(this instanceof Foo)) return new Foo(x);
this.x = x;
}
hello() {
return `hello ${this.x}`;
}
}
If we try to call this class without the new keyword, we get an error:
Cannot call a class as a function
This is because class constructors are designed to create new instances of the class. Invoking them without the new operator is equivalent to calling a regular function.
To allow calling a class constructor without the new keyword, we can use a combination of a constructor function and an arrow function as follows:
class Foo {
constructor(x) {
if (!(this instanceof Foo)) return new Foo(x);
this.x = x;
}
hello() {
return `hello ${this.x}`;
}
}
const FooWithoutNew = () => new Foo(...arguments);
Now, we can call the class constructor without the new keyword using FooWithoutNew:
FooWithoutNew("world").hello(); // "hello world"
However, it's important to note that this approach has some drawbacks. First, it requires creating a separate function, which can be inconvenient. Second, it breaks the constructor's behavior of returning a new instance.
In general, it is recommended to always call class constructors with the new keyword for clarity and consistency.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3