"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can You Call a Class Constructor Without \'new\' in ES6?

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

Published on 2024-11-07
Browse:877

 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}`;
  }
}

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

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}`;
  }
}
  • Always call the class with new:
(new Foo("world")).hello(); // "hello world"
  • Wrap the class in a function and call with new:
var FooWrapper = function(...args) { return new Foo(...args) };
FooWrapper("world").hello(); // "hello world"
Latest tutorial More>

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