【问题标题】:how to get javascript class properties list如何获取javascript类属性列表
【发布时间】:2018-09-06 09:51:39
【问题描述】:

我有 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)

但它不起作用。在这个例子中我应该得到的只是姓名和出生日期。没有其他方法或吸气剂。

【问题讨论】:

    标签: javascript class ecmascript-6 properties


    【解决方案1】:

    问题是您使用 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) 会做你想做的事,但那是荒谬的。

    【讨论】:

    • 非常感谢。它工作正常^_^。我已经尝试了大约两个小时没有任何结果。但现在我明白了我的问题。我必须使用类的实例,而不是类本身。非常感谢您的帮助。
    猜你喜欢
    • 2010-10-18
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 2021-03-26
    • 2013-11-06
    相关资源
    最近更新 更多