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.