如何在 nodejs 调试控制台中更改对象实例的字符串表示形式。有没有toString()
我可以覆盖的方法(比如在.NET中)?
考虑以下代码:
class SomeObject{
constructor(){
this._varA = "some text";
this._varB = 12345;
this._varC = "some more text";
this._varD = true;
this._varE = 0.45;
}
toString(){
return "custom textual rapresentation of my object";
}
}
var array = [];
array.push(new SomeObject());
array.push(new SomeObject());
array.push(new SomeObject());
console.log(array);
然而,在我研究过的其他环境和编程语言中,覆盖该toString()
方法将显示toString()
(在上面的示例中"custom textual representation of my object"
)的结果,而不是由调试器创建的动态文本表示(在上面的示例代码中是SomeObject {_varA: "some text", _varB: 12345, _varC: "some more text", …}
:) - 我不这样做'不要怀疑一分钟,当未定义自定义替代方案时,它非常有用。
我也意识到console.log(array.toString());
甚至console.log(array.map(t=>t.toString()));
会产生类似于我所追求的东西,但是这会阻止我使用调试导航来导航对象,即。钻入对象图。
如果这不可能,其他人会从中受益吗?如果有足够的兴趣,我可以考虑将其定义和实现为一个特性。