绘制原型链

时间:2014-11-15 03:26:14

标签: javascript inheritance graph tree

是否有可视化图形化JavaScript原型链的方法?

基本上我希望看​​到一个继承树,这样我就可以更好地了解一个大项目是如何工作的。

1 个答案:

答案 0 :(得分: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----------------------------