列出Javascript对象的所有原型属性 [英] List Down All Prototype Properties of an Javascript Object

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

问题描述

还有其他方法可以查找javascript对象的原型属性。让我说我喜欢这个。

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 = undefined;
    this.property2 = undefined;
};

proton.prototype = {

    sample1 : function() {
        return 'something';
    },

    sample2 : function() {
        return 'something';
    }

};

var my_object = new proton();

console.log(Object.keys(my_object));

返回[property1,property2]

returns ["property1", "property2"]

console.log(Object.getOwnPropertyNames(my_object));

返回[property1,property2]

returns ["property1", "property2"]

但我要打印的是对象my_object的原型属性。

But what i want to print is the prototype properties of the object my_object.

['sample1','sample2']

['sample1', 'sample2']

为了让我能够看到该对象的原型属性,我需要console.log(对象),并且从开发人员工具中我可以查找该对象的属性。

In order for me to see the prototype properties of that object i need to console.log(object) and from developer tools i can look up for the properties of that object.

但由于我使用的是第三方库,如phaser.js,react.js,create.js
所以我不知道创建对象的原型属性列表这个库。

But since I am using third party libraries like phaser.js, react.js, create.js so i don't know the list of the prototype properties of a created object from this libraries.

是否有任何Object的原型函数列出javascript对象的所有prototpye属性?

Is there any prototype function of Object to list down all the prototpye properties of a javascript object?

推荐答案

不是原型方法,但你可以使用 Object.getPrototypeOf 遍历原型链a然后获取每个对象的属性名称。

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"

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

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