instanceof
instanceof 用于判断某个对象是否是另一个对象(构造方法)的实例。instanceof会查找原型链,直到null如果还不是后面这个对象的实例的话就返回false,否则就返回true
1 function instanceofFunc(obj, cons) { 2 // 错误判断 构造函数必须是一个function 其他的均报错 3 if (typeof cons !== 'function') throw new Error('instance error') 4 if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) return false 5 // 获取到原型对象 6 let proto = cons.prototype 7 // 如果obj的原型对象不是null 8 while (obj.__proto__) { 9 if (obj.__proto__ === proto) return true 10 obj = obj.__proto__ 11 } 12 return false 13 } 14 15 console.log(instanceofFunc(() => {}, Function)) // true