“未捕获的引用错误:未定义"在类构造函数中 [英] "Uncaught ReferenceError: this is not defined" in class constructor

查看:53
本文介绍了“未捕获的引用错误:未定义"在类构造函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

index.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

"use strict";

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

player.js

"use strict";

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

推荐答案

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

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(arg1, arg2, argN);

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

with whatever arguments the parent constructor needs.

要求,如果执行到constructor函数的末尾,this的值需要被初始化为某个东西.你要么需要在一个基类中(其中 this 是自动初始化的),已经调用了 super() 所以 this 被初始化,或者返回一个替代对象.

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

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

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

You can think of it like constructor functions kind of have an automatic return this at the end of them.

这篇关于“未捕获的引用错误:未定义"在类构造函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆