问题描述
如果我可以使用 obj.constructor.prototype
来访问对象的原型,那么为什么我不能使用 obj.constructor。 prototype.constructor.prototype
来遍历原型链并且必须使用 Object.getPrototypeOf
?
If I can use obj.constructor.prototype
to access the prototype of an object, then why can't I use obj.constructor.prototype.constructor.prototype
to traverse the prototype chain and have to use Object.getPrototypeOf
?
function MyConstructor()
{
this.prop = 1;
}
var o = new MyConstructor();
console.log(o.constructor.prototype) // MyConstructor
console.log(o.constructor.prototype.constructor.prototype) // MyConstructor?
不应该返回MyConstructor的原型 function [native code]}
(在Chrome控制台中)?
Shouldn't it return the prototype of MyConstructor which is function() { [native code] }
(in Chrome console)?
推荐答案
函数
对象:
function Foo(){ this.x = 1 }; // Dummy constructor function
console.log(Foo instanceof Function) // => true; Foo is an instance of global Function constructor
所有原型都是全局 Object
object:
All prototypes are instances of the global Object
object:
console.log(Foo.prototype instanceof Object); // => true
定义构造函数 Foo
它自动具有附加到它的 Foo.prototype
对象,您可以将其视为一个空白对象,其本身,如上所述,继承自全局 Object
对象。换句话说, Foo.prototype
的原型是 Object.prototype
:
When a constructor Foo
is defined, it automatically has a Foo.prototype
object attached to it, which you can think of as a "blank" object that itself, as per the above, inherits from the global Object
object. In other words, the prototype of Foo.prototype
is Object.prototype
:
function Foo(){ this.x = 1 }; // Dummy constructor function
console.log(Foo.prototype); // Foo (object); already exists
console.log(Object.getPrototypeOf(Foo.prototype) === Object.prototype); // => true
由于 Foo.prototype
对象,可以期望其构造函数是全局 Object
构造函数:
Since Foo.prototype
is a blank object, one would expect its constructor to be the global Object
constructor function:
function Foo(){ this.x = 1 }; // Dummy constructor function
console.log(Foo.prototype.constructor) // => function Foo() { this.x = 1; } ??
console.log(Foo.prototype.constructor === Object.prototype.constructor); // => false
However this "blank" object has an explicit self-referential constructor
property that points back to function Foo(){ this.x = 1 }
and overwrites or "masks" the default constructor property you are expecting:
function Foo(){ this.x = 1 }; // Dummy constructor function
delete Foo.prototype.constructor; // Delete explicit constructor property
console.log(Foo.prototype.constructor) // => function Object() { [native code] }
console.log(Foo.prototype.constructor === Object.prototype.constructor); // => true
因此,您不能使用 obj.constructor.prototype
递归遍历原型链并且必须依赖于 Object.getPrototypeOf()
方法。
Therefore you can't use obj.constructor.prototype
recursively to traverse the prototype chain and have to rely on the Object.getPrototypeOf()
method.
这是一个伟大的。
这篇关于使用constructor.prototype遍历原型链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!