【发布时间】:2019-07-20 19:16:25
【问题描述】:
我正在使用 2 个参数(两个点)开始和结束调用 Line 构造函数。点具有 x 和 y 属性。两个构造函数大部分时间都在工作(Point all the time afaik)但是当我调用 Line.getPerpendicular (返回一个新 Line)时,即使将正确的值传递给 Line 构造函数,它的端点值都是 NaN .
我在 Line 构造函数中隔离了点,并且终点最初具有值,但是当我设置 this.end = endPoint 时,this.end 对于 x 和 y 是 NaN。
直接创建点而不是首先将它们分配给值没有帮助。
Line 构造函数大部分时间都在工作。
function line(start, end) {
console.log({ start, end });
// { start: point { x: 97, y: 299 }, end: point { x: 223, y: 341 } }
/*
this.start = start;
this.end = end;
Originally I thought this might be the problem, like I was
passing in end by reference and then it was being gc'd
*/
const ex = end.x;
const ey = end.y;
const endP = Point(ex, ey);
console.log("END POINT", endP); // point { x: 223, y: 341 }
// the Point is definitely constructed
// correctly.
this.start = Point(start.x, start.y);
this.end = endP;
console.log(this);
// line { start: point { x: 97, y: 299 }, end: point { x: NaN, y: NaN } }
}
您可以通过克隆 https://github.com/Sjbrimley26/geometry,运行 npm i,然后 npm run build 来重现。然后只需打开构建的 html 文件并查看控制台即可。
// 编辑 这是显然导致错误的 getPerpendicular 函数,因为 Line 构造函数以其他方式工作,尽管我不明白为什么因为 Line 是因为使用正确的点值调用。
line.prototype.getPerpendicular = function() {
const { slope, length, center } = this;
const inv = -1 * divide(1)(slope);
const { x, y } = center;
const b = subtract(y)(inv * x);
const x0 = x - Math.floor(length);
const y0 = x0 * inv + b;
const x1 = x + Math.floor(length);
const y1 = x1 * inv + b;
console.log({ x0, y0, x1, y1 });
const start = Point(x0, y0);
const end = Point(x1, y1);
console.log({ start, end });
return Line(start, end);
/*
This doesn't work either
return Line(
Point(
x - Math.floor(length),
(x- Math.floor(length)) * inv + b
),
Point(
x + Math.floor(length),
(x + Math.floor(length)) * inv + b
)
);
*/
}
【问题讨论】:
-
每个点创建不应该是“new Point()”吗?
-
如果你冻结它——
this.end = Object.freeze(endP);——有什么东西会抛出吗?这将改变您的终点,您还必须查看(如果打算)或修复(如果不打算)。在进行该测试之前确保所有文件都处于严格模式,否则它会默默地失败。 -
Point 只是一个创建新点(小写)的包装函数。
-
尝试将其切换到严格模式并冻结 endP,但似乎没有任何影响。
-
所有文件都必须处于严格模式,而不仅仅是这个。或者,还有更复杂的
this.end = new Proxy(endP, {set() { throw new Error('no') }});,即使在草率模式下也应该抛出。
标签: javascript oop ecmascript-6 constructor prototypal-inheritance