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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.