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

Can You Call a Class Constructor Without \'new\' in ES6?

Susan Sarandon
Release: 2024-10-26 01:55:02
Original
303 people have browsed it

 Can You Call a Class Constructor Without 'new' in ES6?

Call Class Constructor Without new Keyword in ES6

Given the class definition:

class Foo {
  constructor(x) {
    if (!(this instanceof Foo)) return new Foo(x);
    this.x = x;
  }
  hello() {
    return `hello ${this.x}`;
  }
}
Copy after login

It is not possible to directly call the class constructor without the new keyword. This is because classes in ES6 inherently have a constructor function that is invoked when the class is called.

Invoking a class without new results in an error:

Cannot call a class as a function
Copy after login

This error message clearly indicates that the class constructor can only be called with the new operator, which is required to create a new instance of the class.

To overcome this limitation, consider the following approaches:

  • Use a regular function instead:
function Foo(x) {
  this.x = x;
  this.hello = function() {
    return `hello ${this.x}`;
  }
}
Copy after login
  • Always call the class with new:
(new Foo("world")).hello(); // "hello world"
Copy after login
  • Wrap the class in a function and call with new:
var FooWrapper = function(...args) { return new Foo(...args) };
FooWrapper("world").hello(); // "hello world"
Copy after login

The above is the detailed content of Can You Call a Class Constructor Without \'new\' in ES6?. 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!