Categories
JavaScript Answers

How to call class constructor without new keyword with JavaScript?

Spread the love

Sometimes, we want to call class constructor without new keyword with JavaScript.

In this article, we’ll look at how to call class constructor without new keyword with JavaScript.

How to call class constructor without new keyword with JavaScript?

To call class constructor without new keyword with JavaScript, we can define an arrow function and call it.

For instance, we write

const Foo = (x) => ({
  x,
  hello: () => `hello ${x}`,
  increment: () => Foo(x + 1),
  add: ({ x: y }) => Foo(x + y),
});

console.log(Foo(1).x);
console.log(Foo(1).hello());

to define the Foo arrow function that returns an object with the properties we want.

Then we call Foo to return a new object and access properties from it.

Conclusion

To call class constructor without new keyword with JavaScript, we can define an arrow function and call it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *