Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 how to override toString() method?

In ES5 style javascript, to override the toString method I would simply do the following:

function myFunction() {
}

myFunction.prototype.toString = function() {
    return "My amazing function";
};

var myAmazingFunc = new myFunction();
console.log(myAmazingFunc);

In my current code I use ES6 and my object is now a class (which essentially is a function).

class MyAwesomeClass {
    // awesome code goes here
}

What I have tried to do to override the toString method are the following:

class MyAwesomeClass {
    toString() {
        return "Awesome";
    }
}

And also

class MyAwesomeClass {
    // awesome code goes here
}
MyAwesomeClass.prototype.toString = function() {
    return "Awesome";
};

Also without the prototype - but still it does not seem it's being called. How is this possible in ES6 class?

like image 902
developer82 Avatar asked Nov 05 '18 12:11

developer82


People also ask

Can we override toString method?

We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.

Why should you override the toString () method?

When you print an object, by default the Java compiler invokes the toString() method on the object. So by overriding the toString() method, we can provide meaningful output.

What will happen if we don override toString () method?

There will not be enough information about state or properties of object. So, whenever you use or print a reference variable of type in which toString() method is not overrided, you will get an output like above. You will not get what the object actually has in it.


2 Answers

This actually does work:

class MyAwesomeClass {
  toString() {
    console.log("toString called");
    return "Awesome";
  }
}

console.log(new MyAwesomeClass() + "!!!");

There must be something wrong with how you're testing (hint: console.log doesn't trigger toString).

If you're looking for a way to customize the console.log output, this is only possible in node.js (https://nodejs.org/api/util.html#util_custom_inspection_functions_on_objects), by adding a custom inspect method. This feature is deprecated though as of node 10.

like image 51
georg Avatar answered Oct 24 '22 07:10

georg


The console.log() will not call the toString() method for you... you also need to use the ${}

class MyAwesomeClass {
  toString() {
    console.log("toString called");
    return "Awesome";
  }
}

let e = new MyAwesomeClass();
console.log(`${e}`);
like image 10
Erick Zetinator Avatar answered Oct 24 '22 06:10

Erick Zetinator