如何获取javascript类属性列表

Zuh*_*aha 1 javascript properties class ecmascript-6

我有这个类的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));
Run Code Online (Sandbox Code Playgroud)

我想获取属性列表名称.我试着用这样的东西:

Object.getOwnPropertyNames.call(Student)
Run Code Online (Sandbox Code Playgroud)

但它不起作用.在这个例子中我应该得到的只是name和birthDate.没有其他方法或吸气剂.

dec*_*eze 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));
Run Code Online (Sandbox Code Playgroud)

*如果有的话,Object.getOwnPropertyNames.call(Object, new Student)做你想要的,但这是荒谬的.