我想问一下JavaScript,ES6的班级建设。这可以将类名放在从“母类”扩展的其他类的构造函数中吗?(有点困惑……)
class Brick {
constructor(x,y,graphic,width,height,type,live, speed){
this.x = x
this.y = y
this.graphic = graphic
this.width = width
this.height = height
this.type = type
this.live = live
this.speed = speed
}
print(){
console.log(this.y)
console.log(this.x)
console.log(this.graphic)
console.log(this.width)
console.log(this.height)
console.log(this.type)
console.log(this.live)
}
init(){
console.log('added to board')
}
}现在,我想让wchih类从Brick类扩展到:
class BrickRed extends Brick {
constructor(Brick){
super(...arguments)
this.graphic = "red.jpg"
this.live = 15
}
}我不确定它是否可以,因为我找不到任何教程,如果它是像上面提出的。正是这两行:constructor(Brick)和super(...arguments)
从我看到的教程来看,最好的(也是唯一的)选择是这样做:
class BrickBlue extends Brick {
constructor(x,y,graphic,width,height,type,live, speed){
super(x,y,graphic,width,height,type,live, speed)
this.graphic = "blue.jpg"
this.live = 10
}
}但这看起来很难看,我想改进一下。
发布于 2019-06-26 07:09:46
这可以将类名放在从“母类”扩展的其他类的构造函数中吗?
不是的。正确的方法是你的第二个片段。但是,如果BrickBlue对某些道具进行了硬编码,则不需要在构造函数中传递它们:
class BrickBlue extends Brick {
constructor(x,y,width,height,type,speed){
super(x,y,"blue.jpg",width,height,type,10,speed)
}
}如果你想找的话
class BrickBlue extends Brick {
constructor(args-of-Brick)根本就没有这样的东西。
但这看起来很难看,我想改进一下。
是的,长的参数列表很难看,而且由于JS还不支持命名参数,所以没有什么可以做的。但是,可以考虑将相关参数分组到单独的对象中:
class Brick {
constructor(position, graphic, size, type, behaviour) 其中position类似于{x:10, y:20}等
另一个选项是为整个参数列表提供一个对象,从而模仿命名参数:
class Brick {
constructor({x, y, graphic, width, height, type, live, speed}) {
...
new Brick({
x: 1,
y: 2,
graphic: ...
...
})在派生类中:
class BrickBlue extends Brick {
constructor(args) {
super({
...args,
graphic: 'blue.jpg',
live: 10
})
}https://stackoverflow.com/questions/56767036
复制相似问题