When trying to create a custom .toString() method on the Array prototype, how can you access the actual array that the method is called on?
This approach seems to work:
Array.prototype.toString = () => 'custom';
"" + [1,2,3]; // 'custom'
However, using "this" doesn't yield the desired result:
Array.prototype.toString = () => "0: " + this[0];
"" + [1,2,3]; // 0: undefined
It's evident that this
does not refer to the array that .toString() is being invoked on. I am unsure of the reason behind it and how to actually access the array.
As a side note -- I am aware of the risks involved in overriding built-in methods like this. I am only doing it for debugging purposes in a complex recursive function where this feature is not crucial to the logic of the code.
To provide some context, I have been logging out arrays in multiple locations and thought altering the default formatting would be simpler than writing lengthier log statements each time. However, it turned out to be more complicated than anticipated, so now I am looking to resolve this issue as it feels like a basic concept that I should understand well.