【问题标题】:Uncaught TypeError: class heritage this.MyClass is not an object or null未捕获的 TypeError:类继承 this.MyClass 不是对象或 null
【发布时间】:2020-09-25 09:57:14
【问题描述】:

我正在尝试从模块内的另一个类扩展一个类。代码如下:

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");
      }
    },
}

在结果控制台中抛出 TypeError: Uncaught TypeError: class heritage this.MyClass is not an object or null 指的是*行。你能帮我解决这个问题吗?

【问题讨论】:

  • 不,不是m/M不一致,只是这里的错字,很抱歉(已编辑)
  • 如果需要使用this,请不要使用箭头函数。
  • @Barmar 这是非常好的建议,谢谢!但不幸的是,它并没有解决我的问题。
  • 您不能在方法调用之外使用this。创建对象时没有可用的this

标签: javascript class inheritance ecmascript-6


【解决方案1】:

this 仅在调用对象的方法时设置,在初始化对象时不可用。

您也不能在赋值之后引用变量af,而不是在创建文字期间。

所以你需要把它分开。在对象字面量中定义第一个类,其余的需要赋值,以便它们可以引用变量。

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();

【讨论】:

    猜你喜欢
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多