1

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.

ballenf
  • 894
  • 10
  • 19
  • Looks like a duplicate of [*What does “this” refer to in arrow functions in ES6?*](http://stackoverflow.com/questions/28371982/what-does-this-refer-to-in-arrow-functions-in-es6) – adeneo Oct 02 '16 at 20:21
  • Yeah, it does, once you know that this being in an arrow function is relevant to the answer. My former self didn't even know that use of the arrow function had anything to do with the problem, so I wouldn't have searched on that phrase or looked at those questions. Probably also why when I searched for 30+ minutes on the topic and read every suggested link, nothing helpful came up. – ballenf Oct 03 '16 at 04:16

3 Answers3

6

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());
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

this is not defined in arrow functions.

As stated here:

An arrow function does not create its own this context, so this has the original meaning from the enclosing context.

Ouroborus
  • 16,237
  • 4
  • 39
  • 62
  • Thanks. That rings a bell now, but I don't usually use `this` so it's never been an issue before. – ballenf Oct 02 '16 at 19:54
1

Short array functions in es2015 doesn't have literal this. so use

Array.prototype.toString = function() {
 return  "0: " + this[0];
}
Emre Sakarya
  • 122
  • 5