如何遍历对象原型链中的所有属性? [英] How to iterate over all properties in object's prototype chain?

查看:467
本文介绍了如何遍历对象原型链中的所有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个es6-class实例,我需要获取其所有属性(以及继承的属性).有没有一种方法可以遍历原型链?

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"

推荐答案

...(以及继承的属性).有没有一种方法可以遍历原型链?

...(and inherited properties too). Is there a way to do this without traversing prototype chain?

如果它们是不可枚举的,则不是,就像您的b属性一样.要枚举不可枚举的属性(!),必须使用getOwnPropertyNames(和getOwnPropertySymbols),要包含继承的属性,必须遍历原型链.

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.

这不是问题:

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 != Object.prototype; o = Object.getPrototypeOf(o)) {
  for (let name of Object.getOwnPropertyNames(o)) {
    allNames.add(name);
  }
}
console.log(Array.from(allNames));

请注意,我假设您想跳过Object.prototype上的那些内容,例如toStringhasOwnProperty等.如果要包含这些内容,请将循环条件更改为o != null(如果您喜欢这种情况,只需将o更改为).

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).

这篇关于如何遍历对象原型链中的所有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆