0

My class has a method whose name is a string. But it seems not enumerable! Even Object.getOwnPropertyNames doesn't work. So, how do I get the method name/key?

class MyClass {
    'hello/world'() {
        console.log("You just called 'hello/world'");
    }
}

const my = new MyClass();

// For in loop
let keys = [];

for (let key in my) {
   keys.push(key);
}

console.log('For in loop: ' + keys);

// Object.getOwnPropertyNames
console.log('Object.getOwnPropertyNames: ' + Object.getOwnPropertyNames(my));

// Call the method
my['hello/world']();
tscpp
  • 1,298
  • 2
  • 12
  • 35
  • The methods of the class are not added to the instance. `MyClass.prototype.hasOwnProperty("hello/world")` is true – adiga May 16 '21 at 12:51
  • Unrelated, but please make it a habit to use the semi-colon statement separators. You would not want to leave this task to the automatic semi-colon insertion algorithm, which has some pitfalls. – trincot May 16 '21 at 12:55
  • 1
    This link might help you https://stackoverflow.com/questions/31054910/get-functions-methods-of-a-class/31055217 – Murugan Shankar May 16 '21 at 13:03

1 Answers1

3

The method is not an owned property of the instance object my. It is an inherited property that is defined on the prototype, and so getOwnPropertyNames will not find it.

You can list it with this code:

console.log('Object.getOwnPropertyNames: ' + 
            Object.getOwnPropertyNames(Object.getPrototypeOf(my)));

Or:

console.log('Object.getOwnPropertyNames: ' + 
            Object.getOwnPropertyNames(MyClass.prototype));
trincot
  • 317,000
  • 35
  • 244
  • 286