How can I see a Javascript object's prototype chain?

后端 未结 2 407
-上瘾入骨i
-上瘾入骨i 2021-02-02 12:51

Given the following code:

function a() {}
function b() {}
b.prototype = new a();
var b1 = new b();

We can stay that a has been add

2条回答
  •  北海茫月
    2021-02-02 13:27

    edit — This answer is from 2010, and quite obsolete. Since then the language has added the Object.getPrototypeOf() API, which vastly simplifies the process.


    You could use the "constructor" property of the object to find the prototype there, and then chain along that until you reached the end of the rainbow.

    function getPrototypes(o) {
      return (function gp(o, protos) {
        var c = o.constructor;
        if (c.prototype) {
          protos.push(c.prototype);
          return gp(c.prototype, protos);
        }
        return protos;
      })(o, []);
    }
    

    (maybe) (or maybe not :-) give me a sec) (well crap; I think it's possible but ignore that code)

    [edit] wow this is totally blowing my mind - that function's close but not quite right; setting up a chain of prototypes is weird and I'm feeling scared and lonely. I suggest paying attention only to the awesome @CMS above.

提交回复
热议问题