javascript get all methods of class

How to get all methods of a class in JavaScript

If you are working with JavaScript, you may come across a situation where you need to get all the methods of a class. There are several ways to achieve this and I will discuss them below.

Method 1: Using Object.getOwnPropertyNames()

The first method is by using the Object.getOwnPropertyNames() method which returns an array of all properties (including methods) found directly in a given object.


class MyClass {
  myMethod() {
    console.log('Hello World!');
  }
}

const methods = Object.getOwnPropertyNames(MyClass.prototype);
console.log(methods); // Output: ["constructor", "myMethod"]

In the above example, we created a class called MyClass which has one method called myMethod(). We then used Object.getOwnPropertyNames() to get all the methods of the class and stored them in the methods variable. Finally, we printed the methods array to the console.

Method 2: Using Object.keys()

The second method is by using the Object.keys() method which returns an array of all enumerable property names found directly upon a given object.


class MyClass {
  myMethod() {
    console.log('Hello World!');
  }
}

const methods = Object.keys(MyClass.prototype);
console.log(methods); // Output: ["myMethod"]

In the above example, we used the same MyClass with the myMethod() method. We then used Object.keys() to get all the methods of the class and stored them in the methods variable. Finally, we printed the methods array to the console.

Method 3: Using Reflect.ownKeys()

The third method is by using the Reflect.ownKeys() method which returns an array of all property names found directly upon a given object, including non-enumerable properties.


class MyClass {
  myMethod() {
    console.log('Hello World!');
  }
}

const methods = Reflect.ownKeys(MyClass.prototype);
console.log(methods); // Output: ["constructor", "myMethod"]

In the above example, we used the same MyClass with the myMethod() method. We then used Reflect.ownKeys() to get all the methods of the class and stored them in the methods variable. Finally, we printed the methods array to the console.

Conclusion

These are some of the ways to get all the methods of a class in JavaScript. Depending on your use case, one method may be more suitable than others. You can try them out and see which one works best for you.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe