zoukankan      html  css  js  c++  java
  • 获取对象的所有属性,不管是否可遍历,不管是自身的还是原型链上的

    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));
    
  • 相关阅读:
    SQL
    第九章
    第三章 表单
    第二章 表格,列表,媒体元素
    HTML5基础
    Java第一本书总复习
    字符串
    人机猜拳
    类的无参方法
    类和对象
  • 原文地址:https://www.cnblogs.com/aisowe/p/15250093.html
Copyright © 2011-2022 走看看