本文介绍了如何查看 Javascript 对象的原型链?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码:

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

我们可以保留 a 已添加到 b 的原型链.伟大的.而且,以下所有内容都是正确的:

We can stay that a has been added to b's prototype chain. Great. And, all the following are true:

b1 instanceof b
b1 instanceof a
b1 instanceof Object

我的问题是,如果我们不提前知道 b1 的起源怎么办?我们如何发现其原型链的成员?理想情况下,我想要一个像 [b, a, Object]["b", "a", "Object"] 这样的数组.

My question is, what if we don't know the origins of b1 ahead of time? How can we discover the members of its prototype chain? Ideally I'd like an array like [b, a, Object] or ["b", "a", "Object"].

这可能吗?我相信我已经在 SO 某处看到了一个答案,它描述了如何找到这个,但我一生都无法再次找到它.

Is this possible? I believe I've seen an answer somewhere on SO that described how to find out just this but I can't for the life of me find it again.

推荐答案

嗯,对象之间的原型链接([[Prototype]])是内部的,一些实现,比如 Mozilla,暴露了它作为 obj.__proto__.

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

Object.getPrototypeOf ECMAScript 第 5 版的方法正是您所需要的,但目前大多数 JavaScript 引擎都没有实现.

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.

看看 John Resig 的这个实现,它有一个陷阱,它依赖于不支持__proto__的引擎的constructor属性:

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;
    };
  }
}

请记住,这不是 100% 可靠的,因为 constructor 属性在任何对象上都是可变的.

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

这篇关于如何查看 Javascript 对象的原型链?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:51