首页 > 解决方案 > Javascript 类作为对象的孩子

问题描述

我正在尝试用 JavaScript 制作一个图形库。我想创建一个Rectangle类,但我不想将它放在全局范围内,因为我的所有函数等都在一个名为L2D.

这是我的代码:

// "primitive" objects
L2D.Vec2 = (x, y) => {
    this.x = x;
    this.y = y;
}

// interfaces
L2D.Drawable = () => {
    this.fillColor = '#FFF';
    this.outlineColor = '#000';
}

L2D.Transformable = () => {
    this.position = L2D.Vec2(0, 0);
}

L2D.Shape = () => {
    L2D.Drawable(); L2D.Transformable();

    this.vertices = [];

    this.draw = (context) => {
        context.beginPath();
        for (let i in this.vertices) {
            let v = this.vertices[vert]
            if (i == 0) context.moveTo(v.x, v.y);
            else context.lineTo(v.x, v.y);
        }
        context.closePath();

        if (this.fillColor) {
            context.fillStyle = this.fillColor;
            context.fill();
        }
        if (this.outlineColor) {
            context.strokeStyle = this.outlineColor;
            context.fill();
        }
    }
}

// classes
L2D.Rectangle = (x, y, w, h) => {
    L2D.Shape();

    this.vertices = [
        L2D.Vec2(x, y),
        L2D.Vec2(x + w, y),
        L2D.Vec2(x + w, y + h),
        L2D.Vec2(x, y + h)
    ]
}

问题是,我不能打电话new L2D.Rectangle(x, y, w, h)。我收到一个错误:

Uncaught TypeError: L2D.Rectangle is not a constructor

我试过做function L2D.Rectangleand class L2D.Rectangle,但都导致错误(抱怨那个点)。

我怎样才能实现我想要做的事情?

标签: javascript

解决方案


箭头函数不能重新绑定 this 上下文。this 已经绑定到词法范围。对于新手来说,你应该有简单的功能。

L2D.Rectangle = function(x, y, w, h) {};

推荐阅读