简体   繁体   English

是否可以在不初始化类的情况下访问类属性?

[英]Is it possible to access class properties without initialising the class?

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. 说我有一个定义属性hello的类,我想访问它以检查它是否已实现并且分配给它的类型正确。 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. 问题是,由于所有非static类属性都绑定到实例,因此如果不实例化该类,我将无法获取它们,而这是无法做到的。

In this situation, is it possible to access hello ? 在这种情况下,可以访问hello吗?

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

In this situation, is it possible to access hello ? 在这种情况下,可以访问hello吗?

Not without using a JavaScript parser (like IDEs do to try to infer instance mbmers). 并非没有使用JavaScript解析器(就像IDE会尝试推断实例mbmers一样)。 hello , as you say, doesn't exist as a property until/unless an instance is created. 就像您说的, hello直到/除非创建了一个实例才作为属性存在。 With a parser, you can (usually) determine what the property names will be, perhaps sometimes their initial values, but that's all. 使用解析器,您可以(通常)确定属性名称是什么,也许有时是它们的初始值,仅此而已。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM