简体   繁体   中英

Why Foo.prototype.isPrototypeOf(Foo) returns false?

I'm trying to execute below lines in chrome console.

function Foo() {}
console.log(Foo.prototype.isPrototypeOf(Foo)); // false
console.log(Object.prototype.isPrototypeOf(Object)); //true

The second line prints false while third line prints true. Can someone explain why?

It happens because all Objects is an object, even its prototype.

But the Foo's prototype (Foo.prototype) is an object different from Foo.

See the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

Foo.prototype is not the prototype of the Foo function itself. It is the prototype of any object created using new Foo() . The function Foo 's prototype is just Function.prototype .

console.log(Function.prototype.isPrototypeOf(Foo)); // true
console.log(Foo.prototype.isPrototypeOf(new Foo())); // true

In the case of Object.prototype, this is the very top of the prototype chain and will return true for anything that doesn't otherwise explicitly break the prototype chain. In the case of Object, since it's a constructor function:

console.log(typeof Object); // function
console.log(Object.__proto__ === Function.prototype); // true

And because Function.prototype is itself an object, then:

console.log(Object.__proto__.__proto__ === Object.prototype); // true

This is why console.log(Object.prototype.isPrototypeOf(Object)); is true, because Object.prototype exists within the prototype chain of the Object constructor function. Specifically it's the prototype of the prototype of the function.

Here is a diagram of how these objects and functions are related. Blue rectangles represent objects, rounded green rectangles are functions (which are a special type of object). The thick black lines are the prototype chain of each object, and the dashed lines show how objects are related using the .prototype property of constructor functions. JavaScript原型链

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM