是否有现有的方法可以直观地绘制 JavaScript 原型(prototype)链?
基本上,我希望看到一个继承树,以便我可以更好地了解大型项目的工作原理。
最佳答案
您可以编写一个简单的函数并向其发送任何对象以查看其原型(prototype)链:
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----------------------------
关于javascript - 绘制原型(prototype)链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26942192/