假设我有一个Person看起来像这样的类:
class Person {
constructor(
public firstName: string,
public lastName: string,
public age: number
) {}
}
Run Code Online (Sandbox Code Playgroud)
是否可以覆盖toString()此类中的方法,因此我可以执行以下操作?
function alertMessage(message: string) {
alert(message);
}
alertMessage(new Person('John', 'Smith', 20));
Run Code Online (Sandbox Code Playgroud)
这个覆盖可能看起来像这样:
public toString(): string {
return this.firstName + ' ' + this.lastName;
}
Run Code Online (Sandbox Code Playgroud)
编辑:这实际上有效.请参阅下面的答案了解详情
如何在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);
Run Code Online (Sandbox Code Playgroud)
但是在我工作的其他环境和编程语言中,覆盖该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()));会产生类似于我所追求的东西,但是这会阻止我使用调试导航来浏览对象,即.钻入对象图.
如果这是不可能的,其他人会从中受益吗?如果有足够的兴趣,我可以考虑定义和实现它作为一个功能.
javascript debugging node.js visual-studio-code vscode-debugger