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. Prototype and Inheritance
  4. Create Object
  5. Object Literal Expression
  6. Create Object with Parent X
  7. Get/Set Prototype
  8. Prevent Adding Property
  9. Determine Type of Object
  10. Clone Object
  11. Test Object Equality
  12. Add Method to Prototype
  13. Object Object
  14. 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 in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog