Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get functions (methods) of a class [duplicate]

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 
like image 421
Jan Avatar asked Jun 25 '15 15:06

Jan


People also ask

How do you access the methods of a class?

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.

What is the duplicate method?

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.

What is a duplicate class?

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.

How do you find the function of one class in another class?

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.


1 Answers

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.

like image 143
Felix Kling Avatar answered Sep 21 '22 20:09

Felix Kling