之前可能被问过,但我正在创建一个Vector看起来像这样的数学类型:
class Vec2 {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x || 0;
this.y = y || 0;
}
magnitude(): number {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
// etc
}
我希望能够做到这一点:
let v1 = new Vec2(5, 5);
let v2 = v1; // this currently copies by reference instead of by value
v2.x = 10; // as a result v1.x is now also 10, whereas I want it to stay 5
这可以做到吗?我知道我可以创建一个显式copy函数,但我更愿意确保 equals 有效,这样我就不会在忘记调用时意外修改现有向量copy。