Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A function to print prototype chain for a given object

Tags:

javascript

Sometimes I get lost in prototype chain of my JavaScript objects, so I would like to have a function that would print in a friendly way the prototype chain of a given object.

I am using Node.js.

function getPrototypeChain(obj) {
   ....
}
var detail = getPrototypeChain(myobject)
console.log(JSON.stringify(detail))
like image 638
exebook Avatar asked Mar 04 '14 09:03

exebook


People also ask

Which method is used to get prototype of an object?

getPrototypeOf() The Object. getPrototypeOf() method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object.

What is function __ proto __?

Description. The __proto__ getter function exposes the value of the internal [[Prototype]] of an object. For objects created using an object literal, this value is Object. prototype . For objects created using array literals, this value is Array.

What is a prototype function in JavaScript?

Prototypes are the mechanism by which JavaScript objects inherit features from one another. In this article, we explain what a prototype is, how prototype chains work, and how a prototype for an object can be set.


2 Answers

This function shows prototype chain of any object clearly:

function tracePrototypeChainOf(object) {

    var proto = object.constructor.prototype;
    var result = '';

    while (proto) {
        result += ' -> ' + proto.constructor.name;
        proto = Object.getPrototypeOf(proto)
    }

    return result;
}

var trace = tracePrototypeChainOf(document.body)
alert(trace);

tracePrototypeChainOf(document.body) returns "-> HTMLBodyElement -> HTMLElement -> Element -> Node -> EventTarget -> Object"

like image 198
Artem Devlysh Avatar answered Sep 17 '22 19:09

Artem Devlysh


You could use something like the following:

function printPrototype(obj, i) {
    var n = Number(i || 0);
    var indent = Array(2 + n).join("-");

    for(var key in obj) {
        if(obj.hasOwnProperty(key)) {
            console.log(indent, key, ": ", obj[key]);
        }
    }

    if(obj) {
        if(Object.getPrototypeOf) {
            printPrototype(Object.getPrototypeOf(obj), n + 1);
        } else if(obj.__proto__) {
            printPrototype(obj.__proto__, n + 1);
        }
    }
}

http://jsfiddle.net/5fv1tv1x/1/

Call it like so:

printPrototype(myObj);

It may require some modification to fit your exact needs. In node, you may also need some extra guards ( I tested in Chrome so I only needed to guard against 'obj' being undefined before recursing).

like image 24
Jack Avatar answered Sep 17 '22 19:09

Jack