ES6课程建设

时间:2019-06-26 07:05:12

标签: javascript class ecmascript-6

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

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

1 个答案:

答案 0 :(得分:4)

  

可以将类名放在从“母类”扩展的其他类的构造函数中吗?

不。正确的方法是您的第二个片段。但是,如果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
        })
    }