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
"Uncaught ReferenceError: this is not defined" in class constructor
提问by bshaw
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?
我正在使用 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 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.
要求,如果执行到达constructor
函数的末尾,则this
需要将的值初始化为某个值。您要么需要在基类中(this
自动初始化的位置),已调用super()
sothis
已初始化,或return
ed 替代对象。
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.
你可以把它想象成constructor
函数return this
在它们的末尾有一个自动。