获取对象的所有属性,不管是否可遍历,不管是自身的还是原型链上的

index.js

function Person() {
  this.race = "human being"; // 实例属性
}

Person.prototype.color = "yellow"; // 公共属性/原型属性

const instance = new Person();
instance.name = "lilei"; // 实例属性
instance.age = 13; // 实例属性

// 实例不可遍历属性
Object.defineProperty(instance, "gender", {
  value: 1,
  enumerable: false,
});

// all properties of instance
function getAllPropertiesNames(obj) {
  const result = {};
  while (obj) {
    Object.getOwnPropertyNames(obj).forEach((item) => {
      result[item] = obj[item];
    });
    obj = Object.getPrototypeOf(obj);
  }
  return result;
}

console.log(getAllPropertiesNames(instance));

posted on 2021-09-10 09:51  aisowe  阅读(67)  评论(0编辑  收藏  举报

导航