Magic methods of python in javascript

1
Python objects have some magic methods like __init__ , __str__ , __eq__ , __ne__ , __gt__ , __lt__ , __ge__ and __le__ . How to simulate these methods in javascript, when I do console.log(obj) write a custom description of the object?

    
asked by anonymous 11.10.2017 / 00:08

1 answer

4

The closest approach to what you want is the toString method:

class Vector {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  
  toString() {
    return 'Vector(${this.x}, ${this.y})';
  }
}

const v = new Vector(1, 2);

console.log(v);

But realize that it does not work the way you want it to. This is because the toString method is only invoked when JavaScript tries to cast the cast of the object to a string . Because the console.log function also accepts an object, the method does not execute. But if you concatenate the object with an empty string, cast will occur and the result will be as desired:

class Vector {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  
  toString() {
    return 'Vector(${this.x}, ${this.y})';
  }
}

const v = new Vector(1, 2);

console.log(v + '');

Other methods mentioned are methods of operator overloading and JavaScript does not support this.

    
11.10.2017 / 00:18