Is it possible to instantiate a class without a new operator?
With the constructor functions, I can use new.target do something like this:
function Person(name) {
if (!new.target) {
return new Person(name);
}
this.name = name;
}
let p1 = new Person("John");
let p2 = Person("Jack");
This will create an instance of Person without a new operator. Is there a similar way to create an instance of a class without new?
The code below throws TypeError: Class constructor Person cannot be invoked without 'new'.
class Person {
constructor(name) {
if (!new.target) {
return new Person(name);
}
this.name = name;
}
}
let p2 = Person("Jack");