ES6 OOP 从父级继承方法 class

ES6 OOP inheriting methods from parent class

我有一些简单的代码:

'use strict';

class GameObject {
    constructor(element){
        this.element = element;
}

    render(width,height,color){
        let newEl = document.createElement(this.element);
        newEl.style.width = width;
        newEl.style.height = height;
        newEl.style.backgroundColor = color;
        document.body.appendChild(newEl);
    }
}

class Circle extends GameObject{
    constructor(element){
       super()
        this.element = element;
   }



   //render(){}

}

圆圈 Class 目前可以访问 GameObjects 的渲染方法 我希望它具有将元素变为圆形的附加功能,即 elem.style.borderRadius = 50% 但是,如果我添加渲染方法在 Circle Class 上它覆盖了原来的方法。如何保留原始继承的 render() 方法并在子 class 上为其添加功能?无需从父级复制和粘贴渲染方法 class?

更新: 我试过使用 super() 方法,它抛出以下错误 index.js:24 Uncaught SyntaxError: 'super' keyword unexpected here

class Circle extends GameObject{
constructor(element){
    super()
    this.element = element;
}

render(){
    super()

   }

}

super()调用构造函数,其他方法需要调用super.methodName;参见例如the MDN guide。在你的情况下:

render() {
  super.render()
}

从 parent 渲染你可以 return 渲染元素。所以 - 在 child class Circle 你可以添加额外的 requried 样式…

class GameObject {
  constructor(element) {
    this.element = element;
  }

  render(width, height, color) {
    let newEl = document.createElement(this.element);
    newEl.style.width = width;
    newEl.style.height = height;
    newEl.style.backgroundColor = color;
    document.body.appendChild(newEl);
    return newEl
  }
}

class Circle extends GameObject {
  constructor(element) {
    super(element)
  }
  
  render(width, height, color) {
    let e = super.render(width, height, color)
    e.style.borderRadius = "50%"
  }
}

let c = new Circle('div')
c.render('40px', '40px', '#FF0000')

存储新创建的元素的一些修改方式。

class GameObject {
  constructor(element) {
    this.element = element;
  }

  render(width, height, color) {
    this.newEl = document.createElement(this.element);
    this.newEl.style.width = width;
    this.newEl.style.height = height;
    this.newEl.style.backgroundColor = color;
    document.body.appendChild(this.newEl);
  }
}

class Circle extends GameObject {
  constructor(element) {
    super(element)
  }
  
  render() {
    super.render(...arguments)
    this.newEl.style.borderRadius = "50%"
  }
}

let c = new Circle('div')
c.render('40px', '40px', '#BB0000')