Operator overload exists in Javascript?
What the question asks does not exist in Javascript. It is called Perator overloading, or, in Portuguese, overload of operators.
The behavior of Javascript operators is fixed to a set of types, with no possibility of extension.
To date, binary arithmetic operators such as +
, -
, *
, /
at all times will evaluate to a numerical value. It is even possible to customize as an arbitrary value used as operating is converted to the primitive number
, but nothing can be done to cause the operator to result in a value other than number
.
A crazy example that modifies the conversion process to type number
using Symbol.toPrimitive
:
class Vector2 {
constructor(x, y) {
Object.assign(this, { x, y });
}
// Modificamos a forma como objetos `Vector2` tornam-se primitivos
[Symbol.toPrimitive](hint) {
switch (hint) {
case 'number':
return Math.hypot(this.x, this.y);
default:
return `Vector2(${this.x}, ${this.y})`
}
}
}
const v1 = new Vector2(3, 4);
const v2 = new Vector2(6, 8);
// Convertendo para string:
console.log(`${v1}; ${v2}`);
// Conversão para primitivo `number` é feita implicitamente pelo `-`.
// v2 é convertido para 10; v1 é convertido para 5.
console.log(v2 - v1);
In short: there is no way to overload. There is even proposal so that this will one day be part of the language, but it is still far from becoming reality.
Alternatives
Since it is not possible to modify the behavior of language operators, one possible solution is to create functions that encapsulate the operator-analogous logic for an arbitrary type.
In the case of two-dimensional vectors, you could implement functions such as vec2_add
, vec2_mult
, etc.. This has already been demonstrated in the other reply.
Another alternative is to define the methods corresponding to the operators in the class itself. Instead of +
, one can have a method add
in the class itself. Thus:
class Vector2 {
constructor(x, y) {
Object.assign(this, { x, y });
}
add(other) {
return new Vector2(this.x + other.x, this.y + other.y);
}
}
const v1 = new Vector2(1, 2);
const v2 = new Vector2(5, 6);
const v3 = v1.add(v2);
console.log(v3); // { x: 6, y: 8 }
The advantage of this approach is that multiple calls can be chained.
Of course it’s not as pretty as wearing the +
, but it’s what I see as most expressive in current Javascript.
Unfortunately, it is not possible
– epx