You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constisObj=obj=>((typeofobj==='object')||(typeofobj==='function'))&&obj!==nullfunctionmyInstanceOf(instance,Ctor){if(!isObj(Ctor))// 右侧必须为对象thrownewTypeError('Right-hand side of 'instanceof' is not an object')constinstOfHandler=Ctor[Symbol.hasInstance]// 右侧有[Symbol.hasInstance]方法,则返回其执行结果if(typeofinstOfHandler==='function')returninstOfHandler(instance)// 右侧无[Symbol.hasInstance]方法且不是函数的,返回falseif(typeofCtor!=='function')returnfalse// 左侧实例不是对象类型,返回falseif(!isObj(instance))returnfalse// 右侧函数必须有原型constrightP=Ctor.prototypeif(!isObj(rightP))thrownewTypeError(`Function has non-object prototype '${String(rightP)}' in instanceof check`)// 在实例原型连上查找是否有Ctor原型,有则返回true// 知道找到原型链顶级还没有,则返回falsewhile(instance!==null){instance=Object.getPrototypeOf(instance)if(instance===null)returnfalseif(instance===rightP)returntrue}}
instanceof的底层实现原理及手动实现
作用
instanceof
用于检测右侧构造函数的原型是否存在于左侧对象的原型链上。Symbol.hasInstance
ES6
新增的内置Symbol,用作对象方法标识符,该方法用于检测任意对象是否为拥有该方法对象的实例。instanceof
操作符优先使用该Symbol
对应的属性。这样一来
instanceof
右侧并非必须为函数,对象也可以的。示例代码如下:手写实现
ECMAScript定义
标准出处 -> ECMAScript#instanceof
InstanceofOperator ( V, target )
OrdinaryHasInstance ( C, O )
The text was updated successfully, but these errors were encountered: