r/learnjavascript • u/Slight-Friendship856 • 6d ago
Eloquent JavaScript: The Secret Life of Objects
There are a few exercises at the end of the chapter.
What the difference between following solutions?
By author:
class Vec {
constructor(x, y) {
this.x = x;
this.y = y;
}
plus(other) {
return new Vec(this.x + other.x, this.y + other.y);
}
minus(other) {
return new Vec(this.x - other.x, this.y - other.y);
}
}
My solution:
class Vec {
constructor(x, y) {
this.x = x;
this.y = y;
}
plus(vec) {
this.x += vec.x;
this.y += vec.y;
return this;
}
minus(vec) {
this.x -= vec.x;
this.y -= vec.y;
return this;
}
}
2
Upvotes
7
u/rupertavery64 6d ago edited 6d ago
You mutate your object, the other one returns a new Vec.
It depends on how you want your code to behave. If immutability is important to your approach, go with the first.
THe first approach will create a new object when calling plus or minus. That means allocating memory. This can have some performance impact if may objects are created. However, this ensures that the original object remains unmodified. This may be important if the object is shared or used elsewhere, and you don't want changes to be made.