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
/** * mock instanceof * @param {Any} left * @param {Any} right */const_instanceof=(left,right)=>{if(!left||!right)returnnewError('lack of parameter')letproto=left.__proto__right=right.prototype||{}while(proto){if(proto===right){returntrue}else{proto=proto.__proto__}}returnfalse}
The text was updated successfully, but these errors were encountered:
instanceof
用来判断左侧变量是否为右边变量的实例,而创造一个实例的new
关键字,其实就是根据构造函数的原型属性prototype
创造新的对象,并以其为上下文执行构造函数。因此,对于实现
instanceof
,我们可以获取左侧变量的构造函数的原型对象,跟右侧变量的原型对象进行比较。但这样只是获取原型链上目标对象的直接父级,还需要逐层递归往原型链上面进行查找。
JS的对象里就有一个属性
__proto__
,指向的就是当前对象的构造函数的原型,我们可以基于此实现instanceof
。The text was updated successfully, but these errors were encountered: