Ben Fletcher Ben Fletcher - 2 months ago 6
Javascript Question

Custom .toString() method on an array

When defining a custom .toString() method on the Array prototype, how do you access the actual array that the method is called on?

This works:

Array.prototype.toString = () => 'custom';
"" + [1,2,3]; // 'custom'


But "this" doesn't work:

Array.prototype.toString = () => "0: " + this[0];
"" + [1,2,3]; // 0: undefined


Clearly
this
isn't referencing the array that .toString() is being called on, but I'm not sure why and not sure how to get at the array.

Side note -- I know how terribly bad it is to override builtin methods like this. I'm doing it for debug of a complex (for my level) recursive function -- the code itself is not relying on this functionality for any logic.

The more detailed background info is that I am logging out an array in many different places and changing the default formatting seemed easier than writing a much longer log statement each time. Turns out I was wrong, but now just want to figure out this issue because it seems like something basic I should know.

Answer

You could use this to access the actual array. But it does not work with this and an arrow function. In this case you need the classic function keyword.

var array = ['first', 'second', 'third'];

Array.prototype.toString = () => "0: " + this[0];
console.log(array.toString());
Array.prototype.toString = function () { return "0: " + this[0] };
console.log(array.toString());

Comments