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

How to Invoke ES6 Classes Without the `new` Keyword?

Susan Sarandon
Release: 2024-10-26 03:18:02
Original
462 people have browsed it

 How to Invoke ES6 Classes Without the `new` Keyword?

ES6: Bypassing the new Keyword for Class Constructor Invocation

In ES6, classes serve not only as blueprints for objects but also embody their constructors. The constructor() function serves as the class body, and its execution is triggered when the class is invoked. However, attempting to call a class without the required new keyword often results in the "Cannot call a class as a function" error message.

Understanding the Constructor Imperative

Classes are inherently tied to the new operator, which ensures that a new instance of the class is created upon instantiation. Invoking a class without new goes against this design principle, leading to the aforementioned error.

Alternative Solutions

If the desired behavior is to allow class invocation with or without new, several alternatives exist:

1. Using a Regular Function Instead of a Class

A regular function can mimic class-like behavior without the new requirement. It can still enforce instance-like behavior using this, but it lacks the encapsulation and inheritance features of classes.

<code class="js">function Foo(x) {
  this.x = x;
  this.hello = function() {
    return this.x;
  };
}</code>
Copy after login

2. Enforcing the new Keyword

If the intended purpose is to always invoke the class with new, there is no need for any workarounds. Simply adhere to the recommended constructor invocation pattern:

<code class="js">(new Foo("world")).hello(); // "hello world"</code>
Copy after login

3. Wrapping the Class with a Regular Function

This approach provides the flexibility to invoke the class with or without new while maintaining the benefits of using classes. The wrapping function always invokes the class constructor with new.

<code class="js">class Foo {
  constructor(x) { this.x = x; }
  hello() { return `hello ${this.x}`; }
}

var _old = Foo;
Foo = function(...args) { return new _old(...args) };

Foo("world").hello();       // "hello world"
(new Foo("world")).hello(); // Also works</code>
Copy after login

The above is the detailed content of How to Invoke ES6 Classes 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!