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

164
Views
How I can convert class instance to string when using new?

I need to achieve the following behavior: So when creating a class instance via new, I received a string, not a class object. How to implement this? Is it even possible?

For example

class ExampleClass{
  constructor(str) {
    this.str = str;
  }
     // some code I guess...
}

const str = new ExampleClass('example')

console.log(str) // 'example'
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Give this a try:

class ExampleClass extends String {}
about 4 years ago · Juan Pablo Isaza Report

0

While using Class with new it create this instance internally and return it

HOW IT WORK INTERNALLY

let ExampleClass = function(_str){
  //this = Object.create(ExampleClass.prototype);
  this.str = _str
  // return this;
}
str = new ExampleClass('EXAMPLE');

Good practice: Can create helper function or getters instead of changing implementation

class ExampleClass{
  constructor(str) {
    this._str = str;
  }
  // some code...
  get str(){return this._str;}
  set str(str){this._str = str;}
  helperFetchStr(){ return this._str;}
}
new ExampleClass('EXAMPLE1').str;
new ExampleClass('EXAMPLE2').helperFetchStr();

Extending the String class. Here prototype will be from string enabling you to perform all string operations directly on str

let similar = new String("EXAMPLE")

class ExampleClass extends String {
  constructor(str) {
    super(str);
  }
  // some code...
}
const str = new ExampleClass('EXAMPLE');
//console.log(str.{STRING_OPERATIONS})
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!