How do I create an object inside the same class, new this ()?

  • 0
    Good afternoon, I still have a habit from other languages ​​that I can do it like this:
    class A  {
      constructor() {
        this.test = Math.random();
      }
      instance() {
        return new this();
      }
    }
    class B extends A {}
    
    const b = new B(); // b.test = 0.3213123213154353
    const c = b.instance(); // c.test = 0.43234871231123


    But this does not work in js, I know what can be created if you specify the class name - return new A (); , but I need polymorphic behavior.

    Please tell me how to implement this?
    JavaScript Claire Nicholson, Sep 10, 2019

  • 1 Answers
  • 0
    return new this.constructor ();



    ??
    Rose Suarez

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!