我从一本书上解决了这个练习,但我有问题(如下)。
给Vec原型两种方法,plus和minus,将另一个向量作为参数,并返回一个新的向量,该向量具有两个向量(this和参数)x和y值的和或差。
将getter属性length添加到计算向量长度的原型,即点(x,y)到原点(0,0)的距离。
// Your code here.
console.log(new Vec(1, 2).plus(new Vec(2, 3)));
// â Vec{x: 3, y: 5}
console.log(new Vec(1, 2).minus(new Vec(2, 3)));
// â Vec{x: -1, y: -1}
console.log(new Vec(3, 4).length);
// â 5
class Vec {
constructor(x, y) {
this.x = x;
this.y = y;
length = Math.sqrt(this.x * this.x + this.y * this.y);
}
plus(v) {
return { x: this.x + v.x, y: this.y + v.y };
}
minus(v) {
return { x: this.x - v.x, y: this.y - v.y };
}
}
console.log(new Vec(1, 2).plus(new Vec(2, 3)));
// â Vec{x: 3, y: 5}
console.log(new Vec(1, 2).minus(new Vec(2, 3)));
// â Vec{x: -1, y: -1}
console.log(new Vec(3, 4).length);
// â 5
这是可行的,但我想改进我的解决方案。如果我改变向量的x或y的值,长度值将是错误的,因为它是在构造函数中计算的。例子:
let vecTest = new Vec(3, 4);
console.log(vecTest.length);
// â 5 (this value is ok)
vecTest.x -= 3;
// the value of x has now changed, but the lenght value has not!
console.log(vecTest.length);
// â 5 (this value is NOT ok)
console.log(Math.sqrt(vecTest.x * vecTest.x + vecTest.y * vecTest.y));
// â 4 (this is what the value should be)
我知道我可以用一个函数来实现这一点,但是有没有一种方法可以只用绑定来实现呢?我试着用这样的原型:
Vec.prototype.length = Math.sqrt(this.x * this.x + this.y * this.y);
我在类外设置了这个值,但它不起作用。”这“事实上是没有定义的。
有什么建议吗?谢谢。