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.Rectangle
and class L2D.Rectangle
,但都导致错误(抱怨那个点)。
我怎样才能实现我想要做的事情?
解决方案
箭头函数不能重新绑定 this 上下文。this 已经绑定到词法范围。对于新手来说,你应该有简单的功能。
L2D.Rectangle = function(x, y, w, h) {};
推荐阅读
- arduino - 交流调光器代码灯泡在闪烁前不发光
- python - 从列表列表中创建一个 numpy 集合数组
- javascript - Microsoft BotBuilder javascript 示例错误
- javascript - 将数据附加到 HTML 文件中
- javascript - JQuery查找和最近找不到最近的输入字段
- javascript - 如何使用导入的 JS 对象数组部署 REST API?
- java - 如何将移位元素功能与插入排序结合起来?
- java - 它显示 JTextArea 类型的 toStringbyPrice(double) 方法未定义。我不知道如何处理
- python - 如何完全获取父项和子项,Python 3.6
- smartcard - 如何从借记卡/信用卡智能卡中获取 PAN(主帐号)