0

I come from python where any class can have functions like __add__, __str__, ecc... to change the behavior of sum, printing, ecc... of the class.

Is there an equivalent in Javascript?

For example:

class A:
    def __init__(self, a):
        self.a = a
    def __add__(self, other):
        return self.a + other.a

How would this script be in javascript?

Andre
  • 1,149
  • 2
  • 10
  • 18

2 Answers2

2

What you are looking for is called "operator overloading". Python uses magic methods for that. Javascript unfortunately does not support this kind of behavior. This question has been answered before, please take a look at this answer.

vonas
  • 51
  • 4
-1

it would be the same, just in JavaScript :P

class A {
  constructor(a) {
    this.a = a
  }
  add(other) {
    return this.a + other.a
  }
}
zavr
  • 2,049
  • 2
  • 18
  • 28
  • if i run `let a = new A(3); let b = new A(5);` and `let c = a + b` i got that c is `[object Object][object Object]` and type of c is `string` – Andre Mar 02 '20 at 20:10
  • 1
    @zavr I think he is referring to the internals of the language, like `toString`, `valueOf` – Roberto Murguia Mar 02 '20 at 20:12
  • I see what you mean with your question. Roberto is right about valueOf. – zavr Mar 02 '20 at 20:12