This is the 23rd day of my participation in the August More Text Challenge

Why do we need Instanceof when we have Typeof?

We all know that typeof can help us determine the typeof data, but when we determine the typeof object, typeof can only tell us that it is object, but can not tell us the specific object class, see the following code. Instanceof solves this problem.

Implementation principle of Instanceof

Before introducing the specific usage of Instanceof, let’s first look at the implementation principle of Instanceof, which can help us better understand its usage. In order for the reader to better understand the code, we need to get to the following preparatory knowledge.

  • Object.prototype.__proto__ === null
  • Object. Prototype is an empty Object

To implement instanceof’s three-step strategy, please distinguish between a prototype and a prototype object. Proto refers to a prototype and prototype refers to a prototype object.

Step 1: Get the prototype of the expression on the left

let leftProto = leftVaule.__proto__;
Copy the code

Step 2: Get the prototype object for the expression on the right

let rightProtoType = rightVaule.prototype;
Copy the code

Step 3: Loop through the left expression’s prototype chain to see if there is a right expression

while (true) {
    if (leftProto === null) {
        return false;
    }
    if (leftProto === rightProtoType) {
        return true;
    }
    // Continue up the left expression's prototype chain
    leftProto = leftProto.__proto__
}
Copy the code

Implement instanceof

A few examples to help you understand Instanceof

function test() {}
console.log(test.__proto__ === Function.prototype); //true
Object instanceof Object // true
Function instanceof Function // true
Function instanceof Object // true
test instanceof test // false
test instanceof Object // true
test instanceof Function // true
Copy the code

To understand the above example accurately, we must use the instanceof principle mentioned above. The trick is to get the prototype of the left expression and the prototype object of the right expression, and determine whether the prototype object of the right expression is in the prototype chain of the left expression.

The resources

Brief introduction to the realization principle of Instanceof and Typeof