javascript 如何枚举es6类方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31423573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to enumerate es6 class methods
提问by eguneys
How can I enumerate methods of an ES6 class? similar to Object.keys
如何枚举 ES6 类的方法?如同Object.keys
Here's an example:
下面是一个例子:
class Callbacks {
method1() {
}
method2() {
}
}
const callbacks = new Callbacks();
callbacks.enumerateMethods(function(method) {
// method1, method2 etc.
});
回答by Andrey Ermakov
Object.keys()
iterates only enumerable properties of the object. And ES6 methods are not. You could use something like getOwnPropertyNames()
. Also methods are defined on prototype of your object so you'd need Object.getPrototypeOf()
to get them. Working example:
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);
}
Please notice that if you use Symbols as method keys you'd need to use getOwnPropertySymbols()
to iterate over them.
请注意,如果您使用 Symbols 作为方法键,则需要使用getOwnPropertySymbols()
它们来迭代它们。
回答by Cerbrus
There is no iterator / getter method like Object.keys
in ES6 (yet?). you can, however, use for-of
to iterate over the keys:
没有像Object.keys
ES6那样的迭代器/getter 方法(还有吗?)。但是,您可以使用for-of
迭代键:
function getKeys(someObject) {
return (for (key of Object.keys(someObject)) [key, someObject[key]]);
}
for (let [key, value] of getKeys(someObject)) {
// use key / value here
}