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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32516204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:32:50  来源:igfitidea点击:

"Uncaught ReferenceError: this is not defined" in class constructor

javascriptecmascript-6

提问by bshaw

I am playing with the new stuff in JavaScript/ES6. I get an Uncaught ReferenceError: this is not defined(...) player.js:5in my code. As far as I see, there are no errors here! Is this a bug? Any workarounds?

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

index.html

索引.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>

entity.js

实体.js

"use strict";

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

player.js

播放器.js

"use strict";

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

回答by loganfsmyth

This is a fact of the new class syntax. Your subclass needs to call super()in order for the class to be properly initialized, e.g.

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

super(arg1, arg2, argN);

with whatever arguments the parent constructor needs.

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

It is required that, if execution reaches the end of a constructorfunction, the value of thisneeds to have been initialized to something. You either need to be in a base class (where thisis auto-initialized), have called super()so thisis initialized, or returned an alternative object.

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

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

You can think of it like constructorfunctions kind of have an automatic return thisat the end of them.

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