最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how to get javascript class properties list - Stack Overflow

programmeradmin5浏览0评论

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 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.

Share Improve this question asked Sep 6, 2018 at 9:51 Zuhair TahaZuhair Taha 3,0322 gold badges37 silver badges37 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

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.

发布评论

评论列表(0)

  1. 暂无评论