javascriptconstructorfactorynew-operatorinstantiation

How to make a class that returns an instance without `new` keyword


I would like to create a class that would work like, for example, the built-in BigInt. So I can do:

BigInt('111')
BigInt('222').toString()

Please guide me on how to code it. I'm using NodeJS with vanilla JavaScript. Thank you so much in advance.


Solution

  • There are several solutions.

    It's probably easiest to create a normal class and then a helper function that creates the object.

    class MyRealClass {
      constructor(name) {
        this.name = name;
      }
      hello() {
        console.log('Hello', this.name);
      }
    }
    
    function creteMyRealClass(name) {
      if (new.target) throw Error("Object should not be called with 'new'");
      return new MyRealClass(name);
    }
    
    
    creteMyRealClass('Alpha').hello();

    Another option is to use a helper function that calls Object.create

    // By declaring an external object with attributes
    // common to all objects of this type, you save memory
    // and execution time
    const MyPrototype = {
      hello() {
        console.log('Hello', this.name);
      },
    };
    
    function createMyPrototype(name) {
      if (new.target) throw Error("Object should not be called with 'new'");
      const obj = Object.create(MyPrototype);
      obj.name = name;
      return obj;
    }
    
    const b = createMyPrototype('Beta');
    b.hello();