Analysis of the realization principle of instanceof and the realization of handwritten instanceof

1. Type judgment.

As we all know, in JavaScript, there are undoubtedly the following three methods to detect the type of a variable. Of course, this article will skip the first two and focus on the implementation principle of instanceof and the implementation of handwritten instanceof.

  • typeof method

 

  • Object.prototype.toString.call()

  • instanceof

2. The realization principle of instanceof.

  • official:

The instanceof operator is used to test whether the constructor 's prototype property appearsanywhere in the object's prototype chain .

  • Vernacular:

If a instanceof B , then a must be an object , and B must be a valid function . When both conditions are met : determine whether the prototype object ( B.prototype ) pointed to by the prototype property of B is on the prototype chain of object a . Returns true if present; false if not present. In short, the principle of instanceof is actually a process of finding the prototype chain .

3. Implementation of handwritten instanceof.

function myInstanceof(left,right){
        //获取(构造)函数的(显式)原型
        let rp = right.prototype;
        //获取对象的(隐式)原型
        left = left.__proto__;
        //判断对象的(隐式)原型是否等于(构造)函数的(显式)原型
        while(true){
          if(left === null){
            return false
          }
          if(left === rp){
            return true
          }
          left = left.__proto__
        }
      }

      let a = /12/;
      let b = '123';
      console.log(a instanceof RegExp,myInstanceof(a,RegExp));  //true,true
      console.log(b instanceof RegExp,myInstanceof(b,RegExp));  //false,false

 

Guess you like

Origin blog.csdn.net/Yi2008yi/article/details/124102143