Javascript类作为对象';孩子
我正在尝试用JavaScript制作一个图形库。我想创建一个Javascript类作为对象';孩子,javascript,Javascript,我正在尝试用JavaScript制作一个图形库。我想创建一个Rectangle类,但我不想让它在全局范围内,因为我的所有函数等都在一个名为L2D的对象中 这是我的代码: // "primitive" objects L2D.Vec2 = (x, y) => { this.x = x; this.y = y; } // interfaces L2D.Drawable = () => { this.fillColor = '#FFF'; this.out
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)
]
}
问题是,我不能调用新的L2D.Rectangle(x,y,w,h)
。我得到一个错误:
Uncaught TypeError: L2D.Rectangle is not a constructor
我尝试过使用函数L2D.Rectangle
和类L2D.Rectangle
,但都会导致错误(抱怨那个点)
如何实现我的目标?箭头函数无法重新绑定此上下文。此字段已绑定到词法范围。对于新手来说,您应该具有普通函数
L2D.Rectangle = function(x, y, w, h) {};
箭头函数无法重新绑定此上下文。此字段已绑定到词法范围。对于新手来说,您应该具有普通函数
L2D.Rectangle = function(x, y, w, h) {};
非常感谢。我认为箭头函数在功能上等同于普通匿名函数,但显然有区别。谢谢!我认为arrow函数在功能上等同于常规匿名函数,但显然存在差异。