如何枚举 ES6 类的方法?如同Object.keys
这是一个例子:
class Callbacks {
method1() {
}
method2() {
}
}
const callbacks = new Callbacks();
callbacks.enumerateMethods(function(method) {
// method1, method2 etc.
});
Object.keys()
仅迭代对象的可枚举属性。而 ES6 方法则不然。你可以使用类似的东西getOwnPropertyNames() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames。此外,方法是在对象的原型上定义的,因此您需要Object.getPrototypeOf()
得到他们。在职的example http://www.es6fiddle.net/ic4ga97x/:
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);
}
请注意,如果您使用符号作为方法键,则需要使用getOwnPropertySymbols() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertySymbols迭代它们。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)