3.Javascript实现instanceof

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
相关文章
相关标签/搜索