The constructor of Object.prototype

落花浮王杯 提交于 2019-12-13 03:57:48

问题


In JavaScript, every object inherits its properties and methods from a specific prototype, where prototypes are objects.

The inheritance forms a prototype chain where (Object.prototype) stands at its top (followed by null which has no properties or methods) and all the objects inherit from it (unless someone else inserts other changes to the prototype chain).

If (Object.prototype) is an object, what is its constructor?

I mean what completes this expression in order to be evaluated to true.

Object.prototype instanceof .....

回答1:


From "this and Object Prototypes" book of "You don't know JS" series by Kyle Simpsion

function Foo() {
    // ...
}

Foo.prototype.constructor === Foo; // true

var a = new Foo();
a.constructor === Foo; // true

The Foo.prototype object by default (at declaration time on line 1 of the snippet!) gets a public, non-enumerable (see Chapter 3) property called .constructor, and this property is a reference back to the function (Foo in this case) that the object is associated with. Moreover, we see that object a created by the "constructor" call new Foo() seems to also have a property on it called .constructor which similarly points to "the function which created it".

Note: This is not actually true. a has no .constructor property on it, and though a.constructor does in fact resolve to the Foo function, "constructor" does not actually mean "was constructed by", as it appears. We'll explain this strangeness shortly.

...

"Objects in JavaScript have an internal property, denoted in the specification as [[Prototype]], which is simply a reference to another object.".

So, Object.prototype itself is not an object. As to your specific question about instanceof:

var a = new Function();
a.prototype instanceof Object; //true
var b = new String();
b.prototype instanceof Object; //false


来源:https://stackoverflow.com/questions/45602544/the-constructor-of-object-prototype

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