Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get methods of class in JavaScript

Tags:

javascript

How to get list of methods defined for a class in js?

class c {
  methodA(){}
  static methodB(){}

  log(){console.log(/*methods*/);}
  static logStatic(){console.log(/*static methods*/)}
}

Thanks

like image 801
Márius Rak Avatar asked Aug 24 '18 18:08

Márius Rak


People also ask

What is get in class in JavaScript?

The get syntax binds an object property to a function that will be called when that property is looked up.

What does get () do in JS?

get() method in JavaScript is used for returning a specific element among all the elements which are present in a map.

How do you create a class method in JavaScript?

Class methods are created with the same syntax as object methods. Use the keyword class to create a class. Always add a constructor() method. Then add any number of methods.

What is a method in JavaScript?

A JavaScript method is a property containing a function definition. Methods are functions stored as object properties. You will typically describe fullName () as a method of the person object, and fullName as a property.

How do you access an object method in JavaScript?

You access an object method with the following syntax: You will typically describe fullName() as a method of the person object, and fullName as a property. The fullName property will execute (as a function) when it is invoked with ().

What is the use of class in JavaScript?

It is a template for JavaScript objects. The example above uses the Car class to create two Car objects. The constructor method is called automatically when a new object is created. If you do not define a constructor method, JavaScript will add an empty constructor method. Class methods are created with the same syntax as object methods.

How to get all methods of an object in HTML document?

An HTML document contains some methods and the task is to get all methods of the object. There are two methods to solve this problem which are discussed below: Create a function which takes object as input. Use typeof operator, which checks if the type of object is function or not. If the type of object is function then it returns the object.


1 Answers

You can use Object.getOwnPropertyNames and filter the instance and static methods:

class c {
  methodA(){}
  static methodB(){}

  log(){console.log(/*methods*/);}
  static logStatic(){console.log(/*static methods*/)}
}
const instanceOnly = Object.getOwnPropertyNames(c.prototype)
    .filter(prop => prop != "constructor");
console.log(instanceOnly);
const staticOnly = Object.getOwnPropertyNames(c)
    .filter(prop => typeof c[prop] === "function");
console.log(staticOnly);
like image 161
NullPointer Avatar answered Sep 21 '22 16:09

NullPointer