Control the output of a console.log when printing an object that extends the string class JS

Viewed 12

I have a class that expands the string class and I was wondering if you could control the output if you were to try to print the object,

Here is my class:

class betterString extends String {
  constructor() {
    super("Test")
    this.RealString = "test 2"
  }
  func() {
    return "Useless Value"
  }
}

and if I initialize the object and try to print it, this is the output:

[String (betterString): 'Test'] { RealString: 'test 2' }

is there a way to make a console.log output "Test" instead of that mess?

1 Answers

Since you are extending String, you will have access to all the methods in the prototype chain. toString() is a method coming from the Object.prototype. It will give you the string representation of your object.

class BetterString extends String {
  constructor() {
    super("Test")
    this.RealString = "test 2"
  }
  func() {
    return "Useless Value"
  }
}

const obj = new BetterString();
console.log(obj.toString());

Related