JavaScript: Show Prototype Chain
Here is a function that returns any object's prototype chain as array.
/* [ xah_get_proto_chain(obj) Take any object, returns a array, the order of elements shows the proto chain. First element is obj itself, last element is root. http://xahlee.info/js/js_show_prototype_chain.html Version 2020-06-25 ] */ const xah_get_proto_chain = ((x) => { const result = [x]; let t = x; while ((t = Reflect.getPrototypeOf(t)) !== null) result.push(t); return result; });
// test const o1 = {k:1}; const o2 = Object.create (o1); o2.k = 2; const o3 = Object.create (o2); o3.k = 3; 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()) ); // [ 2020-06-25T15:50:29.679Z, Date {}, {} ] // 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.