我正在尝试用 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.Rectangle
和class L2D.Rectangle
,但两者都会导致错误(提示该点)。
我怎样才能实现我想要做的事情?
最佳答案
箭头函数无法重新绑定(bind) this 上下文。 this 已经绑定(bind)到词法范围。对于新手来说,您应该拥有简单的功能。
L2D.Rectangle = function(x, y, w, h) {};
关于Javascript 类作为对象的子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50896029/