How can I change the way String or Number casts a class?
For example, I have the class User:
class User {
constructor(name, age) {
this._name = name;
this._age = age;
}
}
How do I convert a class object to String and get the name attribute back when I convert it to String. And if I want to convert the object of the class to Number, it returns the age attribute.
Like this:
const user = new User('Kevin', 23);
console.log(String(user)) // Kevin
console.log(Number(user)) // 23
Thanks!
CodePudding user response:
Use toString
and valueOf
methods.
class User {
constructor(name, age) {
this._name = name;
this._age = age;
}
toString() { return this._name; }
valueOf() { return this._age; }
}
const user = new User('Kevin', 23);
console.log(String(user)) // Kevin
console.log(Number(user)) // 23
CodePudding user response:
I want to know why? It doesn't look like this reduces complexity.
String(user);
Number(user);
user.string;
user.number;
user.name;
user.age;