Search code examples
javascriptnode.jsjavascript-objectsconsole.log

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


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?


Solution

  • Figured it out, this answers what I wanted to do

    it uses the built in module known as util and it can set the default print value for an object

    const util = require('util');
    
    class MyClass {
      constructor(a, b) {
        this.a = a;
        this.b = b;
      }
      [util.inspect.custom]() {
        return `a is ${this.a} and b is ${this.b}`;
      }
    }
    
    const my_object = new MyClass(1, 2);
    console.log(util.inspect(my_object));
    console.log(my_object);
    

    Ciro Santilli was the person to originally answer the question