instanceOf operator principle

definition

The instanceof operator is used to test whether the constructor's prototype property appears anywhere in the object's prototype chain. ——MDN

Simply understood as: instanceofyou can detect whether an instance belongs to a certain type.

function Foo(){
    
    }
const a = new Foo()

a instanceof Foo       // true
a instanceof Object    // true

It can also be used in inheritance relationships to determine whether an instance belongs to its parent type.

function Foo(){
    
    }
function Child(){
    
    }
function Other(){
    
    }
Child.prototype = new Foo     // 继承原型

const b = new Child()
b instanceof Foo       // true
b instanceof Child     // true
b instanceof Other     // false
b instanceof Object    // true

accomplish

prototypeCheck whether the object pointed to by object B is prototypeon the [[ ]] chain of object A.

If it is, return it true, if it is not, return it false. However, there is a special case, when the object B prototypewill nullreport an error (similar to a null pointer exception).

Function mocking A instanceof B:

/**
* @param obj{Object} 测试对象
* @param fun{Function} 构造函数
*/
function instanceOf(A, B) {
    
    
    let obj = A.__proto__
    let fn = B.prototype
    while (true) {
    
    
        if (obj === null) return false
        // 这里重点:当 fn 严格等于 obj 时,则返回 true
        if (fn === obj) return true
        obj = obj.__proto__
    }
}

Guess you like

Origin blog.csdn.net/qq_44880095/article/details/113782282