Magical python methods in javascript

Asked

Viewed 108 times

1

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

  • If you have a project where you want to use several of these methods and have to run client-side, an alternative may be to use Python even in the browser. The Brython project (http://brython.info) allows this.

1 answer

4

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

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

However, note that it does not work as desired. This is because the method toString is only invoked when Javascript attempts to cast of the object to a string. As the function console.log also accepts an object, the method is not executed. But if you concatenate the object with a string empty, the 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 cited are operator overload methods and Javascript does not support this.

  • 1

    The same applies to the method valueOf(), but with numerical return.

Browser other questions tagged

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