JS扩展构造函数类
JS Extended constructor class
我正在学习JS,我创建了一个类Entity
:
class Entity {
constructor(x=0, y=0, dx=0, dy=0, width=50, height=50, solid=false,
color="black", name="entity", id=Math.random()) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.width = width;
this.height = height;
this.solid = solid;
this.color = color;
this.name = name;
this.id = id;
entityList[id] = this;
}
UpdatePosition() {
this.x += this.dx;
this.y += this.dy;
}
Draw() {
ctx.save();
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
ctx.restore();
}
BorderCollision() {
if (this.solid == true) {
if (this.x <= 0) {
this.dx = -this.dx;
}
if (this.x + this.width >= canvas.width) {
this.dx = -this.dx;
}
if (this.y <= 0) {
this.dy = -this.dy;
}
if (this.y + this.height >= canvas.height) {
this.dy = -this.dy;
}
}
}
EntityUpdate() {
this.UpdatePosition();
this.Draw();
this.BorderCollision();
}
}
现在,我想把这个类扩展成一个新的Player
,它有一个新成员:canMove
但我不知道如何做一个新的构造函数,因为当我写constructor(canMove) {this.canMove = canMove; +}
我得到了一个错误:(
如果您正在扩展一个类并定义一个构造函数,如果您想使用this
,则需要调用super()
:
class Player extends Entity {
constructor(canMove) {
// super.constructor(); - NO
super(); // Yes
this.canMove = canMove;
}
}
您可能还希望传递一些参数给super
,并且由于您几乎不想复制整个参数列表,因此您可能希望使用一个选项对象而不是10个单独的参数。
相关文章:
- ES6构造函数返回基类的实例
- 使用Google Visualization动态调用构造函数
- 为什么我需要为扩展函数设置构造函数
- 扩展 pixi.js在构造函数中对访问父的属性进行精灵化
- 在 JavaScript ES2015 中,在扩展类时,我们是否需要显式创建一个新的构造函数,或者我们是否可以只使用父类
- 如何将对象的构造函数传递给 Chrome 扩展程序中的另一个页面
- Javascript子类化,超级构造函数和使用自定义扩展会丢失基类方法
- 将构造函数从单独的文件加载到 Chrome 扩展程序选项页面
- 打字稿覆盖构造函数中的扩展属性
- 检查构造函数调用是否来自扩展类
- 如何在javascript中扩展现有的构造函数
- 如何扩展像Object或Number这样的内建函数的构造函数
- 在扩展类中运行构造函数
- 使用自己的逻辑/旁路构造函数扩展库
- 如何从本机构造函数typescript扩展
- 当我需要使用带参数的构造函数时,如何使用Rhino继承(扩展)Java类?
- 是否“使用严格的”?在构造函数中扩展到原型方法
- 测试主干扩展构造函数继承的好方法是什么?
- JS扩展构造函数类
- 扩展 jQuery 在每个方法调用上调用构造函数