我有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。没有其他方法或吸气剂。
答案 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)
会做您想要的事,但这是荒谬的。