Home > Web Front-end > JS Tutorial > body text

How Can I Call an ES6 Class Constructor Without the \'new\' Keyword?

Patricia Arquette
Release: 2024-10-26 02:27:27
Original
534 people have browsed it

How Can I Call an ES6 Class Constructor Without the

Calling ES6 Class Constructors Without "new"

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>
Copy after login

If we try to call this class without the new keyword, we get an error:

Cannot call a class as a function
Copy after login

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>
Copy after login

Now, we can call the class constructor without the new keyword using FooWithoutNew:

FooWithoutNew("world").hello(); // "hello world"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!