admin管理员组文章数量:1287097
I have an es6-class instance and I need to get all its properties (and inherited properties too). Is there a way to do this without traversing prototype chain?
class A {
get a() {
return 123;
}
}
class B extends A {
get b() {
return 456;
}
}
const b = new B();
for (let prop in b) {
console.log(prop); //nothing
}
console.log(Object.keys(b)); //empty array
console.log(Object.getOwnPropertyNames(b)); //empty array
console.log(Reflect.ownKeys(b)); //empty array
console.log(Object.keys(Object.getPrototypeOf(b))); //empty array
console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(b))); //["contructor", "b"] -- without "a"
console.log(Reflect.ownKeys(Object.getPrototypeOf(b))); //["contructor", "b"] -- without "a"
I have an es6-class instance and I need to get all its properties (and inherited properties too). Is there a way to do this without traversing prototype chain?
class A {
get a() {
return 123;
}
}
class B extends A {
get b() {
return 456;
}
}
const b = new B();
for (let prop in b) {
console.log(prop); //nothing
}
console.log(Object.keys(b)); //empty array
console.log(Object.getOwnPropertyNames(b)); //empty array
console.log(Reflect.ownKeys(b)); //empty array
console.log(Object.keys(Object.getPrototypeOf(b))); //empty array
console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(b))); //["contructor", "b"] -- without "a"
console.log(Reflect.ownKeys(Object.getPrototypeOf(b))); //["contructor", "b"] -- without "a"
Share
Improve this question
asked Oct 18, 2016 at 7:31
Digger2000Digger2000
5464 silver badges17 bronze badges
0
1 Answer
Reset to default 16...(and inherited properties too). Is there a way to do this without traversing prototype chain?
Not if they're non-enumerable, as your b
property is. To enumerate non-enumerable properties (!), you have to use getOwnPropertyNames
(and getOwnPropertySymbols
), and to include inherited ones, you have to loop through the prototype chain.
Which isn't a problem:
class A {
get a() {
return 123;
}
}
class B extends A {
get b() {
return 456;
}
}
const b = new B();
let allNames = new Set();
for (let o = b; o && o != Object.prototype; o = Object.getPrototypeOf(o)) {
for (let name of Object.getOwnPropertyNames(o)) {
allNames.add(name);
}
}
console.log(Array.from(allNames));
Note that I assumed you wanted to skip the ones on Object.prototype
like toString
, hasOwnProperty
, and such. If you want to include those, change the loop condition to o != null
(or just o
if you like that sort of thing).
本文标签: javascriptHow to iterate over all properties in object39s prototype chainStack Overflow
版权声明:本文标题:javascript - How to iterate over all properties in object's prototype chain? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741266080a2368489.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论