【问题标题】:Graphing a prototype chain绘制原型链
【发布时间】:2014-11-15 03:26:14
【问题描述】:

是否有现成的方法来可视化地绘制 JavaScript 原型链?

基本上我希望看​​到一个继承树,以便更好地了解大型项目的工作原理。

【问题讨论】:

    标签: javascript inheritance graph tree


    【解决方案1】:

    您可以编写一个简单的函数并将任何对象发送给它以查看它的原型链:

    function printPrototypeChain(o,order)
    {
        /*
           order is an optional parameter, you can send it "PtoC" to print the prototype chain in the Parent to Child order. The default order is Child to Parent.
        */
        var a = [];
        var t = o;
        while(t)
        {
           a.push(t);
           t = Object.getPrototypeOf(t);
        }
        if(order==="PtoC")
        {
           a.reverse();
        }
        for(var i =0; i<a.length; i++)
        {
           console.log(a[i]);
        }
    }
    
    var o = { y: 3};
    
    function f(x)
    {
      this.x = x;
    }
    
    var F = new f(2);
    
    printPrototypeChain(F);
    
    --------------------------------OUTPUT-----------------------------
    f {x: 2, y: 3} 
    Object {y: 3} 
    Object {} 
    --------------------------END OF OUTPUT---------------------------- 
    
    printPrototypeChain(F,"PtoC");
    
    --------------------------------OUTPUT-----------------------------
    Object {} 
    Object {y: 3} 
    f {x: 2, y: 3} 
    --------------------------END OF OUTPUT----------------------------
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      • 2012-07-02
      • 2016-04-10
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多