遍历ES6类的方法和属性 [英] Iterate through methods and properties of an ES6 class
问题描述
因此,随着使用JavaScript的新框架的增长,许多人都采用了ECMAScript 6 shim或TypeScript,它具有许多新功能.我的问题是这样:
So with the growth of new frameworks with JavaScript many have adopted ECMAScript 6 shim's or TypeScript, with many new features. My question is this:
如何遍历ES6类的方法/属性?
How does one iterate over the methods/properties of an ES6 class?
例如(带有对象)
var obj = {
prop: 'this is a property',
something: 256,
method: function() { console.log('you have invoked a method'); }
}
for (var key in obj) {
console.log(key);
}
// => 'prop'
// => 'something'
// => 'method'
(含课程)
class MyClass {
constructor() {
this.prop = 'prop';
this.something = 256;
}
method() {
console.log('you have invoked a method');
}
}
如何列出MyClass
的方法以及其属性(可选)?
How do I list the methods MyClass
has, and optionally its properties as well?
推荐答案
constructor
和任何已定义的方法都是该类的prototype
对象的不可枚举属性.
The constructor
and any defined methods are non-enumerable properties of the class's prototype
object.
因此,您可以使用以下方法获取名称的数组(无需构造类的实例):
You can therefore get an array of the names (without constructing an instance of the class) with:
Object.getOwnPropertyNames(MyClass.prototype)
如果不创建实例就无法获取属性,但是这样做可以使用Object.keys
函数,该函数仅返回对象的可枚举属性:
You cannot obtain the properties without creating an instance, but having done so you can use the Object.keys
function which returns only the enumerable properties of an object:
Object.keys(myInstance)
AFAIK没有标准方法来同时获取原型的不可枚举属性和实例的可枚举属性.
AFAIK there's no standard way to obtain both the non-enumerable properties from the prototype and the enumerable properties of the instance together.
这篇关于遍历ES6类的方法和属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!