如何获取javascript类的属性列表

时间:2018-09-06 09:51:39

标签: javascript class ecmascript-6 properties

我有JavaScript这样的课程:

class Student {
    constructor(name, birthDate) {
        this.name = name;
        this.birthDate = birthDate;
    }

    get age() {
        return 2018 - this.birthDate;
    }

    display() {
        console.log(`name ${this.name}, birth date: ${this.birthDate}`);
    }
}

console.log(Object.getOwnPropertyNames.call(Student));

我想获取属性列表名称。我试图使用这样的东西:

Object.getOwnPropertyNames.call(Student)

但是它不起作用。在此示例中,我应该得到的只是name和birthDate。没有其他方法或吸气剂。

1 个答案:

答案 0 :(得分:7)

问题是您使用的Object.getOwnPropertyNames错误。您无需在其上使用call,只需对其进行调用。*并且您需要传递Student的实例;类对象本身没有任何属性。这些属性是在构造函数中创建的,通过查看类对象,没有什么可以告诉您实例将具有哪些属性。

class Student {
    constructor(name, birthDate) {
        this.name = name;
        this.birthDate = birthDate;
    }

    get age() {
        return 2018 - this.birthDate;
    }

    display() {
        console.log(`name ${this.name}, birth date: ${this.birthDate}`);
    }
}

console.log(Object.getOwnPropertyNames(new Student));

*如果有任何需要,Object.getOwnPropertyNames.call(Object, new Student)会做您想要的事,但这是荒谬的。

相关问题