TypeScript重写ToString() [英] TypeScript override ToString()
本文介绍了TypeScript重写ToString()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个类 Person
,它看起来像这样:
Let's say I have a class Person
which looks like this:
class Person {
constructor(
public firstName: string,
public lastName: string,
public age: number
) {}
}
是否可以覆盖 toString()
这个类中的方法,所以我可以做类似下面的事情?
Is it possible to override the toString()
method in this class, so I could do something like the following?
function alertMessage(message: string) {
alert(message);
}
alertMessage(new Person('John', 'Smith', 20));
此覆盖可能如下所示:
public toString(): string {
return this.firstName + ' ' + this.lastName;
}
编辑:这实际上有效。有关详细信息,请参阅下面的答案。
推荐答案
覆盖 toString
有点像预期的那样:
Overriding toString
works kind of as expected:
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 wxpected; 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
:
What can sometimes be an issue though is that it is not possible to access the toString
of a parent class:
console.log("" + (new Bar() as Foo));
将在Bar上运行toString,而不是在Foo上运行。
Will run the toString on Bar, not on Foo.
这篇关于TypeScript重写ToString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文