“未捕获的ReferenceError:未定义”在类构造函数中 [英] "Uncaught ReferenceError: this is not defined" in class constructor
问题描述
Uncaught ReferenceError:这没有定义(...)player.js:5
在我的代码。据我所知,这里没有错误!这是一个bug吗?任何解决方法? index.html
< html>
< head>
< script type =text / javascriptsrc =js / entity.js>< / script>
< script type =text / javascriptsrc =js / player.js>< / script>
< link href =css / style.css =stylesheettype =text / css>
< title>测试< / title>
< / head>
< body>
< canvas id =screenwidth = 500 height = 500>< / canvas>
< script type =text / javascript> initialize();< / script>
< / body>
< / html>
entity.js
使用严格;
class Entity {
constructor(){
console.log(Entity);
}
}
player.js
use strict;
class Player extends Entity {
constructor(){
console.log(Created); //< - 这里错误
}
}
这是新类语法的一个事实。您的子类需要调用 super()
才能正确初始化类,例如
super(arg1,arg2,argN);
与父构造函数需要的任何参数。
要求,如果执行到达构造函数
函数的末尾,则
的值需要具有被初始化为某物你需要在一个基类(其中这个
被自动初始化),调用 super()
这个
被初始化,或返回
另一个对象。
class Player extends Entity {
constructor(){
super();
console.log(Created); ; // error here
}
}
你可以想像它构造函数
函数有一个自动返回此结尾的
。
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
}
}
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.
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 return
ed an alternative object.
class Player extends Entity {
constructor() {
super();
console.log("Created"); ;// error here
}
}
You can think of it like constructor
functions kind of have an automatic return this
at the end of them.
这篇关于“未捕获的ReferenceError:未定义”在类构造函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!