Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get javascript class properties list

I have javascript this class :

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. without other methods or getters.

like image 686
Zuhair Taha Avatar asked Sep 06 '18 09:09

Zuhair Taha


1 Answers

The issue is that you're using Object.getOwnPropertyNames wrong. You don't need to use call on it, you just call it.* And you need to pass an instance of 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.

like image 95
deceze Avatar answered Nov 15 '22 10:11

deceze