Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
How to change the way that String or Number cast a class in JavaScript?

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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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;

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!