首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ES6类构造

ES6类构造
EN

Stack Overflow用户
提问于 2019-06-26 07:05:12
回答 1查看 76关注 0票数 1

我想问一下JavaScript,ES6的班级建设。这可以将类名放在从“母类”扩展的其他类的构造函数中吗?(有点困惑……)

代码语言:javascript
复制
  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类扩展到:

代码语言:javascript
复制
  class BrickRed extends Brick {
    constructor(Brick){
      super(...arguments)
      this.graphic = "red.jpg"
      this.live = 15
    }
  }

我不确定它是否可以,因为我找不到任何教程,如果它是像上面提出的。正是这两行:constructor(Brick)super(...arguments)

从我看到的教程来看,最好的(也是唯一的)选择是这样做:

代码语言:javascript
复制
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
    }
  }

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-26 07:09:46

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

不是的。正确的方法是你的第二个片段。但是,如果BrickBlue对某些道具进行了硬编码,则不需要在构造函数中传递它们:

代码语言:javascript
复制
class BrickBlue extends Brick {
    constructor(x,y,width,height,type,speed){
      super(x,y,"blue.jpg",width,height,type,10,speed)
    }
  }

如果你想找的话

代码语言:javascript
复制
class BrickBlue extends Brick {
    constructor(args-of-Brick)

根本就没有这样的东西。

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

是的,长的参数列表很难看,而且由于JS还不支持命名参数,所以没有什么可以做的。但是,可以考虑将相关参数分组到单独的对象中:

代码语言:javascript
复制
class Brick {
   constructor(position, graphic, size, type, behaviour) 

其中position类似于{x:10, y:20}

另一个选项是为整个参数列表提供一个对象,从而模仿命名参数:

代码语言:javascript
复制
class Brick {
    constructor({x, y, graphic, width, height, type, live, speed}) {

...

new Brick({
  x: 1,
  y: 2,
  graphic: ...
  ...
})

在派生类中:

代码语言:javascript
复制
class BrickBlue extends Brick {
    constructor(args) {
        super({
            ...args,
            graphic: 'blue.jpg',
            live: 10
        })
    }
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56767036

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档