Javascript 类型脚本重写ToString()
假设我有一个类Javascript 类型脚本重写ToString(),javascript,typescript,overriding,tostring,Javascript,Typescript,Overriding,Tostring,假设我有一个类Person,看起来像这样: class Person { constructor( public firstName: string, public lastName: string, public age: number ) {} } public toString(): string { return this.firstName + ' ' + this.lastName; } 是否可以重写此类中的
Person
,看起来像这样:
class Person {
constructor(
public firstName: string,
public lastName: string,
public age: number
) {}
}
public toString(): string {
return this.firstName + ' ' + this.lastName;
}
是否可以重写此类中的toString()
方法,以便执行以下操作
function alertMessage(message: string) {
alert(message);
}
alertMessage(new Person('John', 'Smith', 20));
此覆盖可能如下所示:
class Person {
constructor(
public firstName: string,
public lastName: string,
public age: number
) {}
}
public toString(): string {
return this.firstName + ' ' + this.lastName;
}
编辑:这确实有效。有关详细信息,请参见下面的答案。覆盖
toString
的工作方式与预期类似:
class Foo {
private id: number = 23423;
public toString = () : string => {
return `Foo (id: ${this.id})`;
}
}
class Bar extends Foo {
private name:string = "Some name";
public toString = () : string => {
return `Bar (${this.name})`;
}
}
let a: Foo = new Foo();
// Calling log like this will not automatically invoke toString
console.log(a); // outputs: Foo { id: 23423, toString: [Function] }
// To string will be called when concatenating strings
console.log("" + a); // outputs: Foo (id: 23423)
console.log(`${a}`); // outputs: Foo (id: 23423)
// and for overridden toString in subclass..
let b: Bar = new Bar();
console.log(b); // outputs: Bar { id: 23423, toString: [Function], name: 'Some name' }
console.log("" + b); // outputs: Bar (Some name)
console.log(`${b}`); // outputs: Bar (Some name)
// This also works as expected; toString is run on Bar instance.
let c: Foo = new Bar();
console.log(c); // outputs: Bar { id: 23423, toString: [Function], name: 'Some name' }
console.log("" + c); // outputs: Bar (Some name)
console.log(`${c}`); // outputs: Bar (Some name)
但有时可能出现的问题是,无法访问父类的toString
:
console.log("" + (new Bar() as Foo));
将在Bar上运行toString,而不是在Foo上 正如@Kruga所指出的,该示例实际上似乎在运行时JavaScript中工作。唯一的问题是 TS2345:类型为“Person”的参数不能分配给类型为“string”的参数 要解析此消息,您必须:
- 显式调用
.toString()
- 或者用字符串连接对象(例如
或`${obj}`
)obj+'
- 或者像任何时候一样使用
(不建议使用,因为这样会失去类型安全性)obj
code
module Entidades{export class eEpisodio{public Id:numer}}code
如果我尝试使用我的toString()方法添加一些属性,它不起作用,它似乎找不到Id属性(或任何属性),我更新了答案。您可能遇到的问题是将toString定义为函数。将其定义为lambda属性可能会更好(就像我在新的更详尽的示例中所做的那样)。非常有用,谢谢@Nypan是否有一个pro参数可以使用public-toString=():string=>{
而不是public-toString():string{
?是的,使用t():=>
确保此
将是您在toString重写中所期望的。您可以继续阅读以了解更多有关此的信息。但基本区别在于,箭头函数不绑定它们自己的this。在这种情况下,“用空字符串连接对象”对我很有效,可以显式调用toString()
在我看来,与使用空字符串进行更“粗糙”的连接相比,它更像是一种最佳实践。