这是mazeContainer.js中的一小段代码,仅包含必要的部分,
import Cell from "./cell.js";
import Player from "./player.js";
export default class Maze {
....
setup(){
for (let rowNum = 0; rowNum < this.rows; rowNum++) {
let row = [];
for (let colNum = 0; colNum < this.columns; colNum++) {
let cell = new Cell(this.ctx, rowNum, colNum, this.cellWidth, this.cellHeight);
row.push(cell);
}
this.grid.push(row);
}
drawMap(){
....
let player = new Player(this.goal, this.lastRow, this.lastColumn);
....
}
}
和player.js -
import Cell from "./cell.js";
export default
class Player extends Cell {
constructor(goal, lastRow, lastColumn) {
super(); // need to manage this statement
this.goal = goal;
this.lastRow = lastRow;
this.lastColumn = lastColumn;
}
....
}
现在,这就是我遇到的麻烦。
我刚刚遇到了super
关键字,到目前为止,我必须知道super
在使用之前需要调用method this
。那不是问题。但是在这里,我还需要为Cell
的构造函数提供所有参数。
如您所见,Cell
该类的构造函数中有很多参数,那么如何将它们传递给new Player(....)
?
有没有更好的方法来实现这一目标?
•extends关键字使动物类的方法在cat类内部可用。
•创建新的Cat对象时调用的构造函数,它接受两个参数,即name和UsesLitter。
•super关键字调用父类的构造函数。在这种情况下,super(name)将Cat类的name参数传递给Animal类的构造函数。当Animal构造函数运行时,它将设置this._name = name;。用于新的Cat实例。
•_usesLitter是Cat类唯一的新属性,因此我们在Cat构造函数中进行设置。
class Animal {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
}
class Cat extends Animal {
constructor(name, usesLitter) {
super(name); // The super keyword calls the constructor of the parent class.
this._usesLitter = usesLitter;
}
get usesLitter() {
return this._usesLitter;
}
}
const bryceCat = new Cat('Bryce', true);
console.log(bryceCat.name); //Output: Bryce
console.log(bryceCat.usesLitter); //Output: true
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句