gpt4 book ai didi

javascript - ES6类构建

转载 作者:行者123 更新时间:2023-11-30 09:13:36 25 4
gpt4 key购买 nike

我想问你关于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
}
}

但这看起来很难看,我想改进它。

最佳答案

Is this ok to put class name inside constructor of other class which extends from "mother class"?

没有。正确的方法是你的第二个片段。但是,如果 BrickBlue 硬编码了一些 props,则无需在构造函数中传递它们:

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)

没有这样的东西。

But this looks ugly, and I want to improve it.

是的,长参数列表很难看,而且由于 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
})
}

关于javascript - ES6类构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56767036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com