Javascript 类作为对象的子对象

标签 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.Rectangleclass L2D.Rectangle,但两者都会导致错误(提示该点)。

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

最佳答案

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

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

关于Javascript 类作为对象的子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50896029/

相关文章:

javascript - 从变量列表(数组)创建重复变量

javascript - 有没有办法将 YouTube API 播放器添加到传单控制窗口?

javascript - 正则表达式@字边界中的字符

javascript - 我不知道我的编码有什么问题。 (javascript)

javascript - $localStorage 数组选择与 ng-options 无法正常工作?

javascript - 如何正确访问 Sencha 模型的属性?

javascript - Div 出现在 > 900px 滚动并停在页脚 div

javascript - 点击 6 次后 ui 路由器刷新崩溃

javascript - JavascriptMVC 的 assertEqual 函数是什么?

javascript - NodeJS 多站点网络抓取