ES6 how to override toString() method?

Viewed 7676

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?

3 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.

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}`);

Are you instantiating the class first? If I create a class:

class myclass {}

and add a prototype, or even just the standard way:

myclass.prototype.toString = () => "hi"
// or, using the class syntax
class myclass {
    toString() {
       return "hi"
    }
}

then I can instantiate the class and it works:

new myclass().toString()
> "hi"

Perhaps you are trying to call it on the static, uninstantiated class itself. In order to do that, you need to add a static method to the class.

class myclass {
    static toString() {
        return "myclass toString"
    }
}

So when you call this on a non-instantiated version of the class, you get the overridden method:

myclass.toString()
> "myclass toString"
Related