简体   繁体   English

如何获取javascript类的属性列表

[英]how to get javascript class properties list

I have javascript this class : 我有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)); 

I want to get properties list names. 我想获取属性列表名称。 I tried to use something like this: 我试图使用这样的东西:

Object.getOwnPropertyNames.call(Student)

But it doesn't work. 但这是行不通的。 what should I get in this example is name and birthDate only. 在此示例中,我应该得到的只是name和birthDate。 without other methods or getters. 无需其他方法或吸气剂。

The issue is that you're using Object.getOwnPropertyNames wrong. 问题是您使用的是Object.getOwnPropertyNames错误。 You don't need to use call on it, you just call it.* And you need to pass an instance of Student ; 您不需要使用call ,只需调用它。*并且您需要传递Student的实例; the class object itself doesn't have any properties. 类对象本身没有任何属性。 The properties are created in the constructor, and nothing can tell you what properties the instance will have from looking at the class object. 这些属性是在构造函数中创建的,从查看类对象来看,没有什么可以告诉您实例将具有哪些属性。

 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)); 

* If anything, Object.getOwnPropertyNames.call(Object, new Student) does what you want, but that's nonsensical. *如果有的话, Object.getOwnPropertyNames.call(Object, new Student)您的要求,但这是荒谬的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM