Skip to content
Advertisement

Uncaught TypeError: class heritage this.MyClass is not an object or null

I’m trying to extend one class from another inside the module. The code looks like that:

let af = {

    MyClass: class {
      constructor() {
        console.log("constructor of my class");
      }
    },

    myNextClass: class extends this.MyClass {    // *
      constructor() {
        console.log("constructor of the next class");
      }
    },

    myOtherClass: class extends this.MyClass {
      constructor() {
        console.log("constructor of the other class");
      }
    },
}

in the result console throws the TypeError: Uncaught TypeError: class heritage this.MyClass is not an object or null referring to line *. Could you help me to fix that?

Advertisement

Answer

this is only set when you’re calling a method of the object, it’s not available when you’re initializing an object.

You also can’t refer to the variable af until after the assignment, not during the creation of the literal.

So you need to split this up. Define the first class in the object literal, the rest require assignments so they can refer to the variable.

let af = {
  MyClass: class {
    constructor() {
      console.log("constructor of my class");
    }
  }
};

af.myNextClass = class extends af.MyClass {
  constructor() {
    super();
    console.log("constructor of the next class");
  }
};

af.myOtherClass = class extends af.MyClass {
  constructor() {
    super();
    console.log("constructor of the other class");
  }
};

new af.MyClass();
new af.myNextClass();
new af.myOtherClass();
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement