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.