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

大城市里の小女人 提交于 2019-12-02 21:35:51

Well, the prototype link between objects ([[Prototype]]) is internal, some implementations, like the Mozilla, expose it as obj.__proto__.

The Object.getPrototypeOf method of the ECMAScript 5th Edition is what you're needing, but it isn't implemented right now on most JavaScript engines.

Give a look to this implementation by John Resig, it has a pitfall, it relies on the constructor property of engines that don't support __proto__:

if ( typeof Object.getPrototypeOf !== "function" ) {
  if ( typeof "test".__proto__ === "object" ) {
    Object.getPrototypeOf = function(object){
      return object.__proto__;
    };
  } else {
    Object.getPrototypeOf = function(object){
      // May break if the constructor has been tampered with
      return object.constructor.prototype;
    };
  }
}

Remember that this is not 100% reliable, since the constructor property is mutable on any object.

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.

Here is a starting point:

Object.prototype.getConstructorNames=function(){
        return Object.keys(window).filter(function(e){
            return typeof window[e]==="function" && this instanceof window[e]},this)
    }

Of course this is really incomplete but I think it will work in most cases and if anyone wants to add to it they can.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!