Javascript:类中的绑定长度

Javascript:类中的绑定长度,javascript,class,Javascript,Class,我从一本书上解决了这个练习,但我有以下问题 编写一个表示二维空间中向量的类Vec。它接受x和y参数编号,并将其保存到同名的属性中 给Vec原型两种方法,加号和减号,将另一个向量作为参数,并返回一个新向量,该向量包含两个向量的this和参数x和y值的和或差 将getter属性length添加到计算向量长度的原型中,即点x,y与原点0,0的距离 然后,练习给出了一个结果应该是什么的示例: // Your code here. console.log(new Vec(1, 2).plus(new V

我从一本书上解决了这个练习,但我有以下问题

编写一个表示二维空间中向量的类Vec。它接受x和y参数编号,并将其保存到同名的属性中

给Vec原型两种方法,加号和减号,将另一个向量作为参数,并返回一个新向量,该向量包含两个向量的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);
我在类之外设置了这个值,但它不起作用。这实际上是未定义的

有什么建议吗?谢谢。

您可以将a用于.length属性:

class Vec {
    constructor(x, y) {
        this.x = x || 0;
        this.y = y || 0;
    }
    get length() {
      return Math.sqrt(this.x * this.x + this.y * this.y);
    }
    // ...
}
实例的.length属性成为动态计算的值

您可能还希望使.plus和.减号函数可链接,而不是返回对象文本

plus(v) {
    this.x += v.x
    this.y += v.y;
    return this;
}
minus(v) {
    this.x -= v.x
    this.y -= v.y;
    return this;
}
现在,您可以编写新的Vec….加….加….减….长度。

您可以使用a作为.length属性:

class Vec {
    constructor(x, y) {
        this.x = x || 0;
        this.y = y || 0;
    }
    get length() {
      return Math.sqrt(this.x * this.x + this.y * this.y);
    }
    // ...
}
实例的.length属性成为动态计算的值

您可能还希望使.plus和.减号函数可链接,而不是返回对象文本

plus(v) {
    this.x += v.x
    this.y += v.y;
    return this;
}
minus(v) {
    this.x -= v.x
    this.y -= v.y;
    return this;
}
现在您可以编写新的Vec…加上…加上…减…长度