I have to dynamically fetch the properties and functions of a ES6 class. Is this even possible?
Using a for...in loop, I only get to loop through the properties of a class instance:
class Foo { constructor() { this.bar = "hi"; } someFunc() { console.log(this.bar); } } var foo = new Foo(); for (var idx in foo) { console.log(idx); }
Output:
bar
Accessing the method of a class To access the method of a class, we need to instantiate a class into an object. Then we can access the method as an instance method of the class as shown in the program below. Here through the self parameter, instance methods can access attributes and other methods on the same object.
Duplicate Method. The Duplicate method makes a duplicate of the object, placing a reference to the new object in a reference variable. The reference variable must be of the same class as, or a superclass of, the object that you want to duplicate.
The "duplicate class" error can also occur when the class is named the same with the same package naming hierarchy, even if one of the classes exists in a directory structure with directory names different than the package names.
To class a method of another class, we need to have the object of that class. Here, we have a class Student that has a method getName() . We access this method from the second class SimpleTesting by using the object of the Student class.
The members of a class are not enumerable. To get them, you have to use Object.getOwnPropertyNames
:
var propertyNames = Object.getOwnPropertyNames(Object.getPrototypeOf(foo)); // or var propertyNames = Object.getOwnPropertyNames(Foo.prototype);
Of course this won't get inherited methods. There is no method that can give you all of them. You'd have to traverse the prototype chain and get the properties for each prototype individually.
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