2

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");
roman465
  • 160
  • 2
  • 5
  • 1
    No. It doesn't matter, it's just the syntax of the language – Samathingamajig Dec 01 '22 at 22:07
  • Please clarify "doesn't seem to be working". It doesn't run? It errors? It produces unexpected output? I suspect there's a very specific error message happening that will answer your question. – CollinD Dec 01 '22 at 22:09
  • @CollinD, I've edited the question. Yes, it throws a specific error which I'm trying to bypass – roman465 Dec 01 '22 at 22:14
  • Do you ask our of curiosity or do you have a real use case for this? – Konrad Dec 01 '22 at 22:16
  • 2
    I wonder if this is a duplicate of [ES6: call class constructor without new keyword](https://stackoverflow.com/questions/30689817/es6-call-class-constructor-without-new-keyword) – Wyck Dec 01 '22 at 22:21
  • 1
    Here's the spec explaining why calling w/o new is erroring. https://tc39.es/ecma262/#sec-ecmascript-function-objects-call-thisargument-argumentslist – CollinD Dec 01 '22 at 22:29
  • 1
    The language does not permit what you're asking for. You can create your own separately named factory function such as `createPerson()` that will do the `new` for you if you really don't want the caller to have to do it. – jfriend00 Dec 02 '22 at 00:45

0 Answers0