Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all functions of es6 class instance [duplicate]

For example, I have some class with some methods:

class SomeClass() {
    someMethod1() {
    }
    someMethod2() {
    }
}

Can I get all function names of this class instance?

Object.keys(new SomeClass()) 

gives me an empty array.

I want to get array like ['someMethod1', 'someMethod2'].

like image 840
Mort Rainey Avatar asked Dec 15 '22 03:12

Mort Rainey


1 Answers

You have to call Object.getOwnPropertyNames() on the prototype property of the class.

class Test {
  methodA() {}
  methodB() {}
}

console.log(Object.getOwnPropertyNames(Test.prototype))

Note that this also includes the constructor, but you can easily exclude it if you want:

class Test {
  methodA() {}
  methodB() {}
}

console.log(
  Object.getOwnPropertyNames(Test.prototype)
    .filter(x => x !== 'constructor')
)
like image 194
Michał Perłakowski Avatar answered Dec 16 '22 17:12

Michał Perłakowski