相关疑难解决方法(0)

TypeScript重写ToString()

假设我有一个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)

编辑:这实际上有效.请参阅下面的答案了解详情

javascript overriding tostring typescript

48
推荐指数
2
解决办法
4万
查看次数

如何在Nodejs调试控制台视图中更改对象的字符串表示形式

如何在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

15
推荐指数
2
解决办法
1000
查看次数