Is there any way to reflect public instance class fields from the javascript class declaration?

120 views Asked by At

The ecmascript candidate spec allows to declare class fields like:

class A {
    foo;
}

or with value assignment like:

class A {
    foo = 'abc';
}

Public instance fields spec on MDN

Is there any way to reflect the list of declared fields names (and assigned value) from the class declaration in similar way how we are able to reflect class methods ? :

class B {
    foo = 'abc';
    boo() {}
}
Object.getOwnPropertyNames(B.prototype) // => ["constructor", "boo"]
1

There are 1 answers

2
nabais On

From what I've searched, you have to create an instance of the class itself to access the values of variables inside the scope.

So you can always list the default values of the constructor if you do the following:

class B {
    foo = 'abc';
    boo() {}
}
Object.getOwnPropertyNames(new B) // => ["foo"]

Hope that helps solving your question