类构造函数中的“未捕获的引用错误:未定义”

IT技术 javascript ecmascript-6
2021-01-18 01:45:37

我正在使用 JavaScript/ES6 中的新东西。Uncaught ReferenceError: this is not defined(...) player.js:5在我的代码中得到一个据我所知,这里没有错误!这是一个错误吗?任何解决方法?

索引.html

<html>
    <head>
        <script type="text/javascript" src="js/entity.js"></script>
        <script type="text/javascript" src="js/player.js"></script>
        <link href="css/style.css" rel="stylesheet" type="text/css">
        <title>Test</title>
    </head>
    <body>
        <canvas id="screen" width=500 height=500></canvas>
        <script type="text/javascript">initialize();</script>
    </body>
</html>

实体.js

"use strict";

class Entity {
    constructor() {
        console.log("Entity");
    }
}

播放器.js

"use strict";

class Player extends Entity {
    constructor() {
        console.log("Created"); // <- error here
    }
}
1个回答

这是新类语法的事实。您的子类需要调用super()才能正确初始化该类,例如

super(arg1, arg2, argN);

使用父构造函数需要的任何参数。

要求,如果执行到达constructor函数的末尾,则this需要将的值初始化为某个值。您要么需要在基类中(this自动初始化的位置),已调用super()sothis已初始化,或return编辑替代对象。

class Player extends Entity {
  constructor() {
    super();
    console.log("Created"); ;// error here
  }
}

你可以把它想象成constructor函数return this在它们的末尾有一个自动