So with the growth of new frameworks with JavaScript many have adopted ECMAScript 6 shim's or TypeScript, with many new features. 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?
If you would like to iterate directly over the values of the keys of an object, you can define an iterator , just like JavaScipts's default iterators for strings, arrays, typed arrays, Map and Set. JS will attempt to iterate via the default iterator property, which must be defined as Symbol. iterator .
In JavaScript, the for-in loop is a basic control statement that allows you to loop through the properties of an object.
There are two types of Class in ES6: parent class/super class: The class extended to create new class are know as a parent class or super class. child/sub classes: The class are newly created are known as child or sub class. Sub class inherit all the properties from parent class except constructor.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With