如果我可以使用 obj.constructor.prototype 来访问对象的原型
一般情况下你不能。考虑一下这种方法的工作原理:
var proto = MyConstructor.prototype;
// has an (nonenumberable) property "constructor"
proto.hasOwnProperty("constructor"); // `true`
// that points [back] to
proto.constructor; // `function MyConstructor() {…}`
如您所见,这是一个循环属性结构。当你这样做时
var o = new MyConstructor();
// and access
o.constructor; // `function MyConstructor() {…}`
// then it yields the value that is inherited from `proto`
// as `o` doesn't have that property itself:
o.hasOwnProperty("constructor"); // `false`
但这仅适用于像o 这样从原型对象继承constructor 属性的对象,并且该对象具有指向原型对象的有用值。想想
var o = {};
o.constructor = {prototype: o};
哎呀。在此处访问o.constructor.prototype 会产生o 本身,它可能是任何其他无意义的值。结构实际上与上面的MyConstructor.prototype 相同 - 如果您访问proto.constructor.prototype.constructor.prototype[.constructor.prototype…],除了proto,您将不会得到任何其他东西。
那我为什么不能用obj.constructor.prototype.constructor.prototype遍历原型链而必须用Object.getPrototypeOf呢?
因为MyConstructor.prototype) 本身具有constructor 属性,而不是从Object.prototype 继承,所以您被困在循环结构中。要真正获得下一个对象真正的原型链,您必须使用Object.getPrototypeOf。
var o = new MyConstructor();
console.log(o.constructor.prototype) // MyConstructor
实际上应该是MyConstructor.prototype。不过,Chrome 控制台有时会在显示未命名对象的有用标题时感到困惑,而且并不总是正确的。
如果你得到它的原型,它应该产生Object.prototype,当你得到MyConstructor函数本身的原型时,它应该是Function.prototype。请注意,您可以再次通过MyConstructor.constructor.prototype 执行后者……