如何枚举es6类方法

egu*_*eys 34 javascript ecmascript-6

如何枚举ES6类的方法?相近Object.keys

这是一个例子:

class Callbacks {
  method1() {
  }

  method2() {
  }
}

const callbacks = new Callbacks();

callbacks.enumerateMethods(function(method) {
  // method1, method2 etc.
});
Run Code Online (Sandbox Code Playgroud)

And*_*kov 41

Object.keys()仅迭代对象的可枚举属性.而ES6方法则不然.你可以用类似的东西getOwnPropertyNames().此外,还在对象的原型上定义了方法,因此您需要Object.getPrototypeOf()获取它们.工作范例:

for (let name of Object.getOwnPropertyNames(Object.getPrototypeOf(callbacks))) {
    let method = callbacks[name];
    // Supposedly you'd like to skip constructor
    if (!(method instanceof Function) || method === Callbacks) continue;
    console.log(method, name);
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果您使用符号作为方法键,则需要使用它getOwnPropertySymbols()来迭代它们.