JS: Show Prototype Chain

By Xah Lee. Date: . Last updated: .

Here's a function that returns any object's prototype chain as array.

const xah_get_proto_chain = ((x) => {
/* [ take any object, returns a array, the order of elements shows the proto chain. First element is x itself, last element is root.
version 2018-01-29
 ] */
    const result = [x];
    let t = x;
    while ( t !== null ) { result.push (t = Object.getPrototypeOf ( t )); }
    result.pop ();
    return result;});

// --------------------------------------------------
// test

const o1 = {k:1};
const o2 = {k:2,__proto__:o1}; // o2 is now child of o1
const o3 = {k:3,__proto__:o2}; // o3 is now child of o2

console.log ( xah_get_proto_chain( o3 ) );
// [ { k: 3 }, { k: 2 }, { k: 1 }, {} ]

// --------------------------------------------------
// standard builtin objects

console.log ( xah_get_proto_chain([3,4]) );
// [ [ 3, 4 ], [], {} ]

console.log ( xah_get_proto_chain({p:1}) );
// [ { p: 1 }, {} ]

console.log ( xah_get_proto_chain( function f () { return 3 }) );
// [ [Function: f], [Function], {} ]

console.log ( xah_get_proto_chain( new Date()) );
// [ 2018-01-29T18:20:29.508Z, Date {}, {} ]

console.log ( xah_get_proto_chain(3) );
// [ 3, [Number: 0], {} ]

console.log ( xah_get_proto_chain( "abc" ) );
// [ 'abc', [String: ''], {} ]

// note, nodejs prints Object.prototype as {}, same as a newly created object, even though they are different object

console.log ( Object.prototype ); // {}

// similarly, Array.prototype prints as [], etc.

JS Object and Inheritance

  1. Object Overview
  2. Object Type
  3. Find Object's Type
  4. Prototype Chain
  5. Create Object
  6. Object Literal Expr
  7. Create Object with Parent X
  8. Get/Set Parent
  9. Show Prototype Chain
  10. Prevent Adding Property
  11. Clone Object
  12. Test Object Equality
  13. Add Method to Prototype

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials