【发布时间】:2017-04-12 10:59:39
【问题描述】:
在 Typescript 中,我有一个类 Contact,它实现了一个接口 IContact。
我想向Contact 类添加一个属性或函数,它返回两个其他字段(名字和姓氏)的组合。
IContact 接口的定义如下:
export interface IContact {
firstname: string;
lastname: string;
}
Contact 类如下所示:
export class Contact implements IContact {
constructor(
public firstname: string,
public lastname: string
) { }
public fullname(): string {
return this.firstname + " " + this.lastname;
}
}
在我看来,我想输出Contact.fullname() 的结果,但我收到一个错误,即fullname 不是函数。
我确实可以访问该类的所有其他属性。
==== 更新 ===
我将添加一些额外的代码来澄清一些内容。
当我在我的视图中输出fullname 属性时,我尝试了contact.fullname(),但也尝试了contact.fullname,但没有任何结果。
在我的组件中,试图弄清楚发生了什么我试图将fullname 输出到控制台,如下所示:console.log("FULLNAME " +contact.fullname());,但这在控制台中给了我以下消息:EXCEPTION _this.contact.fullname is not a function
===== 已更新答案 ========
正如 Sakuto 所说的那样,联系人列表是由从服务器接收到的一些 json 创建的。通过完全调用它的构造函数来创建一个新实例,我能够输出fullname 属性。
谢谢Sakuto!
【问题讨论】:
-
Contact.fullname().. 你在调用 class.function() 吗?如果是这样,函数需要是静态的.. -
不,我在
Contact类的实例上调用函数。 -
拜托,你能显示你的html吗?
-
问题是如何创建
Contact对象?见 Sakuto 的回答。
标签: angular typescript