Cᴀʟʟᴏᴅᴀᴄɪᴛʏ Cᴀʟʟᴏᴅᴀᴄɪᴛʏ - 5 months ago 24
Javascript Question

Iterate through methods and properties of an ES6 class

So with the growth of new frameworks with JavaScript many have adopted ECMAScript 6 shim's or TypeScript, bring new features closer. My question is this:

How does one iterate over the methods/properties of an ES6 class?

e.g. (with objects)

var obj = {
prop: 'this is a property',
something: 256,
method: function() { console.log('you have invoked a method'); }
}

for (var key in obj) {
console.log(key);
}

// => 'prop'
// => 'something'
// => 'method'


(with classes)

class MyClass {
constructor() {
this.prop = 'prop';
this.something = 256;
}

method() {
console.log('you have invoked a method');
}
}


How do I list the methods
MyClass
has, and optionally its properties as well?

Answer

The constructor and any defined methods are non-enumerable properties of the class's prototype object.

You can therefore get an array of the names (without constructing an instance of the class) with:

Object.getOwnPropertyNames(MyClass.prototype)

You cannot obtain the properties without creating an instance, but having done so you can use the Object.keys function which returns only the enumerable properties of an object:

Object.keys(myInstance)

AFAIK there's no standard way to obtain both the non-enumerable properties from the prototype and the enumerable properties of the instance together.