Reputation: 1629
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?
Upvotes: 0
Views: 125
Reputation: 2128
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.
Upvotes: 1
Reputation: 1523
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
Upvotes: 2