How to make calculations with instances of a class, or even with new instances?

Asked

Viewed 70 times

3

I want to do an operation with two, or more, instances of a class. Is there any way to do this?

Example:

class myClass{
  constructor(a){
    this.a = a
  }
}

var myObj1 = new myClass(2)
var myObj2 = new myClass(3)

//log esperado: {"a": 5}
console.log(myObj1 + myObj2)

//log esperado: {"a": 6}
console.log(new myClass(1) + new myClass(5))

  • 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.

2 answers

3

There’s no way.

Javascript does not allow operator overload, so there is no way you can implement differentiated behavior for the operator +.

Related to this, the method valueOf, which is a method of Object, is how Javascript retrieves the value of its object to use it in arithmetic operations.

If you implement your class as follows:

class myClass{
  constructor(a){
    this.a = a
  }

  valueOf() {
    return this.a
  }
}

It will even be possible to compare the greatness of your objects:

var myObj1 = new myClass(2)
var myObj2 = new myClass(3)

console.log(myObj1 > myObj2) // false
console.log(myObj1 < myObj2) // true

However if you use the operator +, your result will be only 5, and not {'a': 5}

3


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).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.