ES6 OOP继承父类的方法

时间:2017-03-22 06:58:52

标签: javascript oop object es6-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()方法并在子类上添加一个功能?无需从父类复制和粘贴render方法?

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

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

render(){
    super()

   }

}

2 个答案:

答案 0 :(得分:1)

从父渲染中,您可以返回渲染元素。所以 - 在子类Circle中,您可以添加其他需要的样式......

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')

答案 1 :(得分:0)

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

render() {
  super.render()
}