数组上的自定义 .toString() 方法
Custom .toString() method on an array
在 Array 原型上定义自定义 .toString() 方法时,如何访问调用该方法的实际数组?
这个有效:
Array.prototype.toString = () => 'custom';
"" + [1,2,3]; // 'custom'
但是"this"不起作用:
Array.prototype.toString = () => "0: " + this[0];
"" + [1,2,3]; // 0: undefined
显然 this
没有引用正在调用 .toString() 的数组,但我不确定为什么也不确定如何获取该数组。
旁注——我知道像这样覆盖内置方法是多么糟糕。我这样做是为了调试一个复杂的(对于我的水平)递归函数——代码本身不依赖于任何逻辑的这个功能。
更详细的背景信息是我在许多不同的地方注销一个数组并更改默认格式 似乎 比每次编写更长的日志语句更容易。原来我错了,但现在只想弄清楚这个问题,因为这似乎是我应该知道的一些基本知识。
您可以使用 this
访问实际数组。但它不适用于 this
和 arrow function。在这种情况下,您需要经典的 function
关键字。
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());
this
未在箭头函数中定义。
如前所述here:
An arrow function does not create its own this
context, so this
has the original meaning from the enclosing context.
es2015 中的短数组函数没有文字 this
。所以使用
Array.prototype.toString = function() {
return "0: " + this[0];
}
在 Array 原型上定义自定义 .toString() 方法时,如何访问调用该方法的实际数组?
这个有效:
Array.prototype.toString = () => 'custom';
"" + [1,2,3]; // 'custom'
但是"this"不起作用:
Array.prototype.toString = () => "0: " + this[0];
"" + [1,2,3]; // 0: undefined
显然 this
没有引用正在调用 .toString() 的数组,但我不确定为什么也不确定如何获取该数组。
旁注——我知道像这样覆盖内置方法是多么糟糕。我这样做是为了调试一个复杂的(对于我的水平)递归函数——代码本身不依赖于任何逻辑的这个功能。
更详细的背景信息是我在许多不同的地方注销一个数组并更改默认格式 似乎 比每次编写更长的日志语句更容易。原来我错了,但现在只想弄清楚这个问题,因为这似乎是我应该知道的一些基本知识。
您可以使用 this
访问实际数组。但它不适用于 this
和 arrow function。在这种情况下,您需要经典的 function
关键字。
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());
this
未在箭头函数中定义。
如前所述here:
An arrow function does not create its own
this
context, sothis
has the original meaning from the enclosing context.
es2015 中的短数组函数没有文字 this
。所以使用
Array.prototype.toString = function() {
return "0: " + this[0];
}