When I was writing an illustration of the difference between prototype and __proto__, I noticed that the following two operations return the same result:
Function instanceof Object; //true Object instanceof Function; //trueCopy the code
What’s going on here? Start with the instanceof operator.
What exactly is instanceof?
I used to understand that instanceof simply checks if an Object is a new instanceof another Object(e.g. Var a = new Object(), an instanceof Object returns true). But instanceof’s algorithm is actually more complicated than that.
First of all, there is an official w3c explanation (portal, if you are interested), but as always, it is hard to read at a glance…
Some students on Zhihu translated this explanation into a language that adults can understand (portal), and it seems to make some sense:
// If the left side of the instanceof operator is L and the right side is R L instanceof R // if the left side of the instanceof operator is L, the right side of the instanceof operator is R L instanceof R = = = R.p rototype? // Return true if it exists and false otherwiseCopy the code
Note: when the instanceof recursive search L prototype chain, namely, l. __proto__. __proto__. __proto__. __proto__… Until we find it or find the top floor.
Therefore, the calculation rule of instanceof is:
Instanceof checks for the presence of a right-hand Prototype on the __proto__ prototype chain.
Function and Object constructor
Let’s look at the code again to understand:
Function. Constructor === Function; Constructor === Function (); // Constructor === Function (); Function () {} console.log(function.__proto__); Function () {} console.log(function.__proto__); //function() {// this special anonymous function's __proto__ points to the Object prototype. Function.__proto__.__proto__ === object. prototype//true // __proto__ refers to Function prototype, __proto__ === function.prototype; //true Function.prototype === Function.__proto__; //trueCopy the code
When constructors Object and Function encounter instanceof
Back to the “strange phenomenon” in part 1, we can see from the picture above:
Function.__proto__.__proto__ === Object.prototype; //true Object.__proto__ === Function.prototype; //trueCopy the code
Function instanceof Object and Object instanceof Function both return true.
If you’re still confused by the above, just remember these two most important relationships and the rest will follow:
-
All constructors point to functions
-
Function prototype refers to a special anonymous Function, and __proto__ refers to Object.prototype
For the derivation of the prototype / __proto__ relationship, see my last blog post “Three Diagrams to Understand JavaScript prototype objects and prototype chains”.