How to iterate over properties of an instance of an ES6 / 2015 class

given these two classes

class Foo{ f1; get f2(){ return "a"; } } class Bar extends Foo { b1; get b2(){ return "a"; } } let bar = new Bar(); 

What code will get this property list from an instance of bar ? ['f1', 'f2', 'b1', 'b2']

Here is an example of Babel


Update

This should be part of @Marc C's answer:

Using a decorator, I can easily turn an non-enumerable property into an enumerated property:

 class Bar extends Foo { @enumerable() get b2(){ return "a"; } } 

Here is the decorator source:

 function enumerable() { return function(target, key, descriptor) { if (descriptor) { descriptor.enumerable = true; } }; } 

Here is an example of Babel

+5
source share
2 answers

This is not a valid syntax for declaring properties in a class. Instead, declare them in the constructor.

 class Foo { constructor() { this.f1 = undefined; } } 

Then you can get them using Object.keys .

Using experimental functions in Babel will allow you to declare properties using this syntax, but their values ​​must be declared.

 class Foo { f1 = 0; ... } 

As with access to getters, getters are not enumerable by default and cannot be accessed using Object.keys or any similar mechanism. However, you can create enumerated getters using Object.defineProperty .

 Object.defineProperty(bar, 'f2', { get() { return "a"; } }); 

If you use the experimental features of ES7, you can apply decorator to the class method and get the same behavior. See Babel Example .

 class Foo { @enumerable() get b2() { return "a"; } } function enumerable() { return function(target, key, descriptor) { if (descriptor) { descriptor.enumerable = true; } } } 
+5
source

It seems to me that this was answered earlier. You can apply Object.getOwnPropertyNames to an instance and its prototypes:

 function getAllPropertyNames(obj) { let names = []; do { names.push.apply(names, Object.getOwnPropertyNames(obj)); obj = Object.getPrototypeOf(obj); } while(obj !== Object.prototype); return names.filter(name => name !== 'constructor'); } 
0
source

Source: https://habr.com/ru/post/1240117/


All Articles