2

Supposing I have a class like this:

class Foo {
  constructor () {}
  foo () {}
  bar () {}
  baz () {}
}

How can I dynamically get an array containing ["foo", "bar", "baz"] (the order doesn't matter)?

I tried using Object.keys(Foo.prototype). That returns an empty array:

"use strict";

class Foo {
  constructor() {}
  foo() {}
  bar() {}
  baz() {}
}

alert(JSON.stringify(Object.keys(Foo.prototype)));

However, if we do it in the prototype way, it works fine:

function Foo () {};
Foo.prototype.foo = function () {};
Foo.prototype.bar = function () {};
Foo.prototype.baz = function () {};

alert(JSON.stringify(Object.keys(Foo.prototype)));

So, how can I get the same array, but when using the classes?

I guess a solution would be to create a class instance and read the fields from there, but I don't really like it...

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474

0 Answers0