[英]ES6 class construction
我想問您有關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')
}
}
現在,我想使class 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
}
}
但這看起來很丑,我想改進它。
將類名放在從“母類”擴展的其他類的構造函數中可以嗎?
不。 正確的方法是您的第二個片段。 但是,如果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
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.