Javascript 为什么在调用行构造函数时,某些值被初始化为NaN?
我用两个参数(起点和终点)调用一个行构造函数。点具有x和y属性。这两个构造函数大部分时间都在工作(始终指向afaik),但是当我调用Line.getvertical(返回新行)时,即使正确的值被传递到Line构造函数中,它的端点值都是NaN 我在直线构造函数中隔离了点,端点最初有值,但当我设置this.end=endPoint时,this.end对于x和y是NaN 直接创建点而不是首先将其指定给值没有帮助 行构造函数大部分时间都在工作Javascript 为什么在调用行构造函数时,某些值被初始化为NaN?,javascript,oop,ecmascript-6,constructor,prototypal-inheritance,Javascript,Oop,Ecmascript 6,Constructor,Prototypal Inheritance,我用两个参数(起点和终点)调用一个行构造函数。点具有x和y属性。这两个构造函数大部分时间都在工作(始终指向afaik),但是当我调用Line.getvertical(返回新行)时,即使正确的值被传递到Line构造函数中,它的端点值都是NaN 我在直线构造函数中隔离了点,端点最初有值,但当我设置this.end=endPoint时,this.end对于x和y是NaN 直接创建点而不是首先将其指定给值没有帮助 行构造函数大部分时间都在工作 function line(start, end) {
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 } }
}
您可以通过克隆、运行npmi,然后npm运行build来复制。然后打开构建的html文件并查看控制台
//编辑
下面是GetVertical函数,它显然导致了这个错误,因为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
)
);
*/
}
这是什么语言 您是否检查过如果从3行中删除const会发生什么情况?不懂这种语言,我在这里处于不利地位 我假设这是一种不必声明函数参数的语言?在许多语言中,标题应该是函数行(点开始、点结束) 你为什么不初始化这个。用你初始化的方法结束。开始?即:
此.end=点(end.x,end.y) 对于每个点的创建,不应该是“new Point()”吗?如果您冻结它–
this.end=Object.freeze(endP)代码>–有什么东西抛出吗?这可能会改变你的终点,你也必须观察(如果有意)或修复(如果无意)。在执行该测试之前,确保所有文件都处于严格模式,否则它将以静默方式失败。Point只是一个创建新点(小写)的包装函数。尝试将其切换到严格模式并冻结endP,但它似乎没有影响任何内容。您的所有文件都必须处于严格模式,而不仅仅是此文件。或者,还有更复杂的this.end=newproxy(endP,{set(){thrownewerror('no')})代码>,即使在草率模式下也应该抛出。嘿,对不起,我应该更具描述性。这是Javascript,实际上我已经尝试了您之前建议的内容,但没有成功。回想起来,我认为可能最终参数是被垃圾收集的,这就是值NaN的原因,但这也没有帮助。这似乎不是答案,而只是注释。