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.
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.
– jsbueno