重写的toString未被调用:为何Bankaccount.toString未执行?
问题分析与解决方案
你遇到的核心问题很清晰:你的Bankaccount类没有显式重写Object基类的toString方法,所以调用实例的toString时,自然会触发继承自Object.prototype的默认实现,输出[object Object]。
具体原因&解决办法
原因1:完全未定义
toString方法
TypeScript的类默认继承自Object,如果你的类里没有自己实现toString逻辑,就会直接使用父类的版本。原因2:
toString方法定义存在语法/拼写错误
比如你的代码截断部分可能没写完toString,或者出现了拼写错误(比如写成toSting())、语法格式错误,导致方法未被正确识别为类的成员方法。
正确重写toString的示例
只需要在Bankaccount类中添加一个符合规范的toString方法即可,比如:
export class Bankaccount { name: string; iban: string; bic: string; accountNumber: string; customerId: string; type: string; id?: number; constructor( name: string, iban: string, bic: string, accountNumber?: string, customerId?: string, type?: string, id?: number ) { this.name = name; this.iban = iban; this.bic = bic; this.accountNumber = accountNumber || ''; this.customerId = customerId || ''; this.type = type || 'default'; this.id = id; } // 重写toString方法,自定义输出内容 toString(): string { return `Bankaccount(name: ${this.name}, iban: ${this.iban}, bic: ${this.bic}, id: ${this.id})`; } }
这样当你调用new Bankaccount(...)实例的toString()时,就会输出你自定义的结构化字符串,而非默认的[object Object]。
另外要注意两个细节:
- 方法名必须是**
toString**(拼写、大小写完全正确,不能出错) - 方法不需要参数,返回值必须是
string类型(TypeScript会帮你做类型校验)
内容的提问来源于stack exchange,提问作者Mfried
相关产品推荐
相关产品推荐

