MrShoe
MrShoe

Reputation: 27

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?

Upvotes: 0

Views: 640

Answers (2)

MrShoe
MrShoe

Reputation: 27

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

Upvotes: 1

Tushar Shahi
Tushar Shahi

Reputation: 20376

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());

Upvotes: 0

Related Questions