Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 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?

like image 780
Aᴄʜᴇʀᴏɴғᴀɪʟ Avatar asked Jun 12 '16 06:06

Aᴄʜᴇʀᴏɴғᴀɪʟ


People also ask

How do you iterate through properties?

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 .

Which JavaScript statement is loop through the properties in objects?

In JavaScript, the for-in loop is a basic control statement that allows you to loop through the properties of an object.

What are ES6 classes in JavaScript?

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.


1 Answers

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.

like image 55
Alnitak Avatar answered Sep 25 '22 01:09

Alnitak