skip to Main Content

I would like to create a class that would work like for example 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.

2

Answers


  1. To achieve something like this, you will have to use factory functions instead of the usual class constructors. Here is an example:

    function MyBigInt(value) {
        return {
          toString: function() {
            return `My Value: '${value}'`;
          }
        };
      }
      
    console.log(MyBigInt('111').toString()); 
    // Output: My Value: '111'
    
    Login or Signup to reply.
  2. 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();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search