As already said in another answer, Javascript does not support operator overload, so the way is to have a method in your class that sums the values and returns another object with the result:
class myClass {
constructor(a) {
this.a = a;
}
// soma o valor deste objeto com o valor de obj e retorna outro objeto com o resultado
add(obj) {
return new myClass(this.a + obj.a);
}
}
var myObj1 = new myClass(2);
var myObj2 = new myClass(3);
var myObj3 = new myClass(10);
console.log(myObj1.add(myObj2)); // { "a": 5 }
console.log(new myClass(1).add(new myClass(5))); // { "a": 6 }
// somando vários de uma vez
console.log(myObj1.add(myObj2).add(myObj3).add(new myClass(1))); // { "a": 16 }
Similarly, if you wanted to implement the other operations (subtraction, multiplication, etc), you would have to have a method for each:
subtract(obj) {
return new myClass(this.a - obj.a);
}
multiply(obj) {
return new myClass(this.a * obj.a);
}
etc...
One detail is that each call from add
creates a new instance, i.e., obj1.add(obj2)
returns a new object, and both obj1
how much obj2
remain unchanged.
That means on a chained call like obj1.add(obj2).add(obj3).add(obj4)
, various intermediate objects are created, which are only used to make the next call.
But it is also possible to make the method add
modify the instance itself:
class myClass {
constructor(a) {
this.a = a;
}
add(obj) {
this.a += obj.a;
return this;
}
}
var myObj1 = new myClass(2);
var myObj2 = new myClass(3);
var myObj3 = new myClass(10);
// myObj1 é modificado pelas chamadas de add()
myObj1.add(myObj2).add(myObj3).add(new myClass(1));
console.log(myObj1); // { "a": 16 }
Thus, myObj1.add(myObj2)
sum the values of myObj1
and myObj2
, and modifies the very value of myObj1
. I made the method return this
(the instance itself), as it remains possible to chain several calls from add
- and each one of them will update the value of myObj1
, which in the end will have the result of all operations.
That is, you can choose to modify the instance itself or return a new one. Which one to use? Depends.
I also put a semicolon at the end of the lines. It may sound "fresh," and I know that Javascript "accepts" the semicolon code and "works," but it avoids some bizarre situations that can occur if you don’t use them, like that one and that one (see more about this here).
As far as I know no, objects are not numbers, you will probably have to make a method to access the variable a and sum it.
– Ricardo Cenci Fabris