List Down All Prototype Properties of an Javascript Object

后端 未结 2 766
抹茶落季
抹茶落季 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条回答
  •  旧时难觅i
    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

提交回复
热议问题