List Down All Prototype Properties of an Javascript Object

后端 未结 2 740
抹茶落季
抹茶落季 2020-11-27 06:52

Is there any other way to look up for the prototype properties of an javascript object. Lets say I have like this.

function proton() {
    this.property1 = u         


        
相关标签:
2条回答
  • 2020-11-27 07:37

    Not a prototype method, but you can use Object.getPrototypeOf to traverse the prototype chain and then get the own property names of each of those objects.

    function logAllProperties(obj) {
         if (obj == null) return; // recursive approach
         console.log(Object.getOwnPropertyNames(obj));
         logAllProperties(Object.getPrototypeOf(obj));
    }
    logAllProperties(my_object);
    

    Using this, you can also write a function that returns you an array of all the property names:

    function props(obj) {
        var p = [];
        for (; obj != null; obj = Object.getPrototypeOf(obj)) {
            var op = Object.getOwnPropertyNames(obj);
            for (var i=0; i<op.length; i++)
                if (p.indexOf(op[i]) == -1)
                     p.push(op[i]);
        }
        return p;
    }
    console.log(props(my_object)); // ["property1", "property2", "sample1", "sample2", "constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable"
    
    0 讨论(0)
  • 2020-11-27 07:39
    function prototypeProperties(obj) {
      var result = [];
      for (var prop in obj) {
        if (!obj.hasOwnProperty(prop)) {
          result.push(prop);
        }
      }
      return result;
    }
    

    EDIT: This will grab all the properties that were defined on any ancestor. If you want a more granular control of what is defined where, Bergi's suggestion is good.

    0 讨论(0)
提交回复
热议问题