Is it possible to access class properties without initialising the class?

余生颓废 提交于 2019-12-25 00:45:13

问题


I want to access all of the properties of a class that will be defined when the constructor is called, so that I can implement a sort of interface for the class.

Say I had a class that defines the property hello, I would like to access it to check it has been implemented and the type assigned to it is correct. Problem is, since all non-static class properties are tied to an instance, I can't get at them without instantiating the class, which I can't do.

In this situation, is it possible to access hello?

class MyClass {
    constructor () {
        this.hello = 'greetings';
    }
}

回答1:


In this situation, is it possible to access hello?

Not without using a JavaScript parser (like IDEs do to try to infer instance mbmers). hello, as you say, doesn't exist as a property until/unless an instance is created. With a parser, you can (usually) determine what the property names will be, perhaps sometimes their initial values, but that's all.



来源:https://stackoverflow.com/questions/46711922/is-it-possible-to-access-class-properties-without-initialising-the-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!