在ES6中包装类函数和使用super的简单方法

Straightforward way to wrap class function and use super in ES6

本文关键字:super 简单 方法 ES6 包装 包装类 类函数      更新时间:2023-09-26

我正在用ES6编写一个应用程序,并使用babel进行编译。我有一系列的形状对象(正方形,长方形,梯形等)

我希望能够使这些对象中的一些"特殊"对象,例如,有双边框或圆角。但我不想创建每个对象的子类(例如,DoubleBorderRectangle, DoubleBorderSquare)

这似乎是一个介绍装饰器的好地方。

当我想修饰一个使用super.

的方法时,我遇到了一些问题。

例如,我有这样一个类:

class Trapezoid extends Sprite {
    constructor(x, y, width, height) {
        super(x, y, width, height);
        this.type = "Trapezoid";
        //other trapezoid specific functions here.
    }
    draw(ctx) {
        super.draw(ctx);
        //specific code for drawing trapezoid here.
    }
}

现在我想实例化一个特殊的梯形,比如双边框,使用装饰器:

function doubleBorder(shape) {
    shape.draw = function(ctx) {
       //draw the trapezoid. 
       super.draw(ctx);
       //double border drawing stuff here.
    }
    return shape;
}

并实例化:

 let trapezoid = new Trapezoid(0,0,100,100);
 let doubleBorderTrapezoid = doubleBorder(trapezoid);

一个问题是babel不喜欢在类之外使用super。这是可以理解的。是否有一种方法来获得形状的超类,并传递它正确的上下文,而不创建一个一次性对象?

我知道这是旧的,但你可以实现许多方法,所以它归结为风格和代码行。

1)在父类中创建一个函数来添加双轮廓,假设它将被多个子类使用。

2)创建一个装饰器函数数组(超类或特定子类),然后在draw (super或sub)中检查这些函数并应用。

const myDecorator = (ctx) => { ... }
...
draw(ctx) {
  this.decorators.forEach(draw => draw(ctx));
}

根据您的用例,第一个是更干净的OOP,第二个是更多的组合功能学习。