A function to print prototype chain for a given object

前端 未结 2 811
青春惊慌失措
青春惊慌失措 2021-02-05 23:20

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 giv

2条回答
  •  别跟我提以往
    2021-02-06 00:01

    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"

提交回复
热议问题