是否可以在不初始化类的情况下访问类属性? [英] 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.
说我有一个定义属性 hello
的类,我想访问它以检查它是否已实现并且分配给它的类型正确。问题是,由于所有非 static
类属性都绑定到一个实例,因此如果不实例化该类,我将无法获取它们,而这是无法做到的。
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.
在这种情况下,可以访问 hello
吗?
In this situation, is it possible to access hello
?
class MyClass {
constructor () {
this.hello = 'greetings';
}
}
推荐答案
在这种情况下,是否可以访问
你好
?
并非不使用JavaScript解析器(就像IDE试图推断实例mbmers一样)。就像您说的那样,你好
直到/除非创建了一个实例才作为属性存在。使用解析器,您可以(通常)确定属性名称是什么,也许有时是它们的初始值,但仅此而已。
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.
这篇关于是否可以在不初始化类的情况下访问类属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!