Reputation: 7250
I am reading about prototype chaining in JS. I came across this schematic online.
My question is:
Since function A and B are Object of type Function shouldn't there be a Function and a Function.prototype Object somewhere in the inheritance tree?
Upvotes: 0
Views: 52
Reputation: 2640
The constructor functions are not being diagrammed hierarchically in the prototype chain, the Objects they construct are the focus of the diagram.
There is an important distinction (and confusion) in the difference between [[proto]]
(accessible via obj.__proto__
where obj
is any Object
) and the Prototype
property of an object, viz. obj.prototype
.
This snippet may explain:
function A(name){
this.name = name
this.getName = function(){ return name }
}
function B(name){
A.call(this, name)
}
var b = new B('yep')
var anotherB = new B('me too')
console.log(b.getName()) // yep
/* both B & A constructors inherit from Function but B doesn't inherit from A */
console.log(B instanceof Function && A instanceof Function) //true
console.log(B.prototype === A.prototype) //false
console.log(B.__proto__ === A.__proto__) //true
console.log(B instanceof A) //false
/* an instance of B is not an instance of A */
console.log(b instanceof B) //true
console.log(b instanceof A) //false
/* an instance of B has the prototype of B but not the same [[proto]] as B */
console.log(B.prototype.isPrototypeOf(b)) //true
console.log(b.__proto__ === B.__proto__ ) //false
/* instances of B have the same [[proto]] but not the same [[proto]] as B */
console.log(b.__proto__ === anotherB.__proto__ ) //true
function B
does not inherit from function A
. Both function A
and function B
inherit from Function
which inherits from Object
. They both have identical Prototype chains (abbreviated).
function A
: function A
-> Function
-> Object
function B
: function B
-> Function
-> Object
Which is different from the Objects they construct. In the case of the Object returned from function B
, the prototype chain is B
-> A
-> Object
.
Upvotes: 2