已定义函数,但MyFunction不是函数

时间:2018-10-31 16:46:37

标签: javascript typescript ecmascript-6

Person是具有firstNamelastName属性的对象。 我有一个返回一些Person的服务。 为了在Typescript中建模Person,我创建了以下Person.ts类:

export class Person {

    firstName?: string;
    lastName?: string;

    get fullName(): string() {
        return `${firstName} ${lastName}`;
    }

}

我可以使用以下代码检索Person的数组:

this.persons: Array<Person> = this.httpClient.get<Array<Person>>('http://url.of.my.service');

对于Person中的每个this.persons,我都能得到它的名字和姓氏,但是如果我尝试获得其全名,则会出现以下错误:person.fullName is not a function 。 什么意思?

2 个答案:

答案 0 :(得分:3)

您的代码有两个问题。

显而易见的是,fullName不是函数,而是属性,因此应该访问person.fullName而不是person.fullName()

第二个问题是this.httpClient.get<Array<Person>>('http://url.of.my.service');将不返回Person的实例,它将返回可能具有Person字段但不是Person实例和因此属性fullName将不存在,因为您在该调用返回的对象上定义了该属性。 (还猜测它不会直接返回数组,看起来像是返回Observable的Angular服务)

您将需要将对象转换为类的实例,例如使用Object.assign

答案 1 :(得分:1)

get fullName()

这是 getter ,不是常规功能。

当您访问fullName属性时,它将隐式调用该函数并为您提供返回值(它是一个字符串)。

尝试调用fullName()会尝试将该字符串视为一个函数,而不是。

如果您没有定义了get,则可以致电fullName()