Ms.Smith Ms.Smith - 2 years ago 51
Javascript Question

How to get properties just of the prototype chain and not of the object itself?

I have an object like this:

var Animal = function() { };
Animal.prototype.size = 'small';
Animal.prototype.height = '50';

var Mammal = function() { };
Mammal.prototype = new Animal(); = 'rabbit';
Mammal.prototype.nickname = 'aaa';

var Rabbit = function(nickname) {
this.nickname = nickname;
Rabbit.prototype = new Mammal(); = 'bbbbbbb';

var myRabbit = new Rabbit('Cutie');

For this object I want to divide its properties into two groups: its own properties and properties inherited from its prototype chain. So I do this:

function getObj(obj){
var ownKeys = Object.keys(obj); // it's ok, I get 'nickname'

var protoKeys = [];
var props = Object.getOwnPropertyNames(obj); // here I can't get all of the properties

The problem is that the properties names are the same in several cases. And I can't get all properties of prototype chain (name, name, nickname, size, height) as I suppose because of that.

Is there any way to get all prototype chain properties? Or their names must be unique?
Thanks a lot in advance!

Answer Source
var props = [];
var proto = obj;

// We go through a chain of prototypes    
while(proto !== null) {
    if (proto!==null) {
        var tmp = {};
        // For each prototype collect property values
        Object.keys(proto).forEach( function(p) {
            tmp[p] = proto[p];
        proto = proto.__proto__;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download