Home >Web Front-end >JS Tutorial >How Can I Call an ES6 Class Constructor Without the \'new\' Keyword?
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:
<code class="javascript">class Foo { constructor(x) { if (!(this instanceof Foo)) return new Foo(x); this.x = x; } hello() { return `hello ${this.x}`; } }</code>
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:
<code class="javascript">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);</code>
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.
The above is the detailed content of How Can I Call an ES6 Class Constructor Without the \'new\' Keyword?. For more information, please follow other related articles on the PHP Chinese website!