gpt4 book ai didi

javascript - ES6 OOP 从父类继承方法

转载 作者:太空宇宙 更新时间:2023-11-04 15:53:12 25 4
gpt4 key购买 nike

我有一些简单的代码:

'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 类上添加渲染方法,它会覆盖原始方法。如何保留原始继承的 render() 方法并在子类上向其添加功能?无需从父类复制并粘贴渲染方法?

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

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

render(){
super()

}

}

最佳答案

从父渲染中,您可以返回渲染的元素。因此 - 在子类 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')

关于javascript - ES6 OOP 从父类继承方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42944729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com