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.

Object and Inheritance Topic

  1. JS: Object Overview
  2. JS: Object Type
  3. JS: Determine Type of Object
  4. JS: Object Literal Expression
  5. JS: Prototype and Inheritance
  6. JS: Create Object
  7. JS: Create Object with Parent X
  8. JS: Get/Set Prototype
  9. JS: Prevent Adding Property
  10. JS: Clone, Deep Copy Object/Array
  11. JS: Test Equality of Objects
  12. JS: Object Object
  13. JS: Object.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

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

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc