So i want to create a class and add a getter to return something when getting the entire instance instead of a getter on one of the children.
example:
JavaScript
x
14
14
1
class Person {
2
constructor(name){
3
this.name = name
4
}
5
6
get () {
7
return "My name is " + this.name;
8
}
9
}
10
11
const Alexander = new Person("Alexander")
12
13
console.log(Alexander) // My name is Alexander
14
So the above is what i want to achieve, but i am unable to and struggling to find something online like this, unsure if it is possible or my wording is just incorrect.
Advertisement
Answer
The default toString()
function of a class defines what should be printed if the class is converted to a string. You can override that function in the following way:
JavaScript
1
14
14
1
class Person {
2
constructor(name){
3
this.name = name;
4
5
// override function here
6
this.toString = function() {
7
return "My name is " + this.name;
8
}
9
}
10
}
11
12
const Alexander = new Person("Alexander")
13
console.log("" + Alexander) // My name is Alexander
14
But it will only get printed if the object is converted to a string. For example by adding it to a string as in the example above (e.g. "" + object
) or by doing String(object)
or simply object.toString()
.