【发布时间】:2021-11-02 03:38:14
【问题描述】:
我有这段代码 sn-p 可以创建一个盒子数组,我想让它成为通用的,以便它也可以,例如,存储一个三角形。我不太确定我需要使用哪些参数或者我需要如何修改它以便它允许一个三角形。如果我想要三角形和盒子,创建一个三角形数组然后将它们定位成一个盒子似乎会更好,但是我会失去创建简单矩形的灵活性。上下文:这是一个实现 z 缓冲区的程序的 sn-p。
class Box {
/** @member {Object} position of the box storing x,y,z coordinates */
position;
/** @member {Object} size of the box storing width and height */
size;
/** @member {Object} color of the box given in RGB */
color;
constructor (props) {
this.position = props.position;
this.size = props.size;
this.color = props.color;
}
/**
* Check if given point is in box
* @param {Number} px coordinate of the point
* @param {Number} py coordinate of the point
* @return {Boolean} point in box
*/
pointInBox (px,py) {
return this.position.x < px && this.position.x + this.size.width > px
&& this.position.y < py && this.position.y + this.size.height > py;
}
}
const boxes = [
new Box({
position: { x: 50, y: 50, z: 10 },
size: { width: 150, height: 50 },
color: { r: 255, g: 0, b:0 }
}),
new Box({
position: { x: 80, y: 30, z: 5 },
size: { width: 10, height: 150 },
color: { r: 0, g: 255, b:0 }
}),
new Box({
position: { x: 70, y: 70, z: 8 },
size: { width: 50, height: 40 },
color: { r: 0, g: 0, b: 255 }
})
];
console.log({ boxes });
.as-console-wrapper { min-height: 100%!important; top: 0; }
【问题讨论】:
-
使 what 通用?它只是一个数组;为什么不能给它加三角形?
-
不应该一个盒子也有
length,让它实际上是3维的吗?毕竟它有 x、y 和 z 坐标。如果不是,那么它是一个矩形而不是一个盒子。如果打算使用 3D 形状,那么您的意思可能是 Tetrahedron 而不是三角形?
标签: javascript inheritance factory composition es6-class