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
// TypeError: Right-hand side of 'instanceof' is not callable1instanceof({})// TypeError: Function has non-object prototype 'undefined' in instanceof check({})instanceof(()=>{})
varfoo=()=>{}vara={}// TypeError: Function has non-object prototype 'undefined' in instanceof checkainstanceoffoo// 显示增加个`prototype `成员函数(必须是函数)就不报错了foo.prototype=function(){}ainstanceoffoo// false
varfoo=()=>{}vara={}// 显示增加个`prototype `成员函数(必须是函数)就不报错了foo.prototype=function(){}// 自定义Symbol.hasInstance方法Object.defineProperty(foo,Symbol.hasInstance,{value: {}// 不是个方法});// TypeError: object is not a functionainstanceoffoo
functionisInstanceOf(obj,constructor){if(typeofconstructor!=='object'){thrownewTypeError('constructor is not a object')}// Symbol.hasInstance方式if(constructor[Symbol.hasInstance]!==undefined){return!!constructor[Symbol.hasInstance](obj);}// 原型链方式:if(typeofobj!=='object'){returnfalse}if(typeofconstructor!=='function'){thrownewTypeError('constructor is not a function')}if(typeofconstructor.prototype!=='object'){thrownewTypeError('Function has non-object prototype');}while(obj!==null){if(obj===constructor.prototype){returntrue;}obj=Object.getPrototypeOf(obj);}returnfalse;}
一、语法
1.1 基本用法
判断构造函数
constructorFunc
的prototype
属性是否在对象object
的原型链上。1. 作为类型判断的一种方式,
instanceof
操作符不会对object
进行隐式类型转换false
2.
constructorFunc
必须是函数,且可以作为构造函数(即要具有prototype
属性)3. 对于跨全局执行上下文
intanceof
就不能正常工作了不同的全局执行上下文的对象和函数都是不相等的。
1.2 PK
Object.prototype.isPrototypeOf()
Object.prototype.isPrototypeOf()
用于判断对象是否在另一个对象的原型链上。[] instanceof Array
相等于Array.prototype.isPrototypeOf([])
看似可以利用
Object.prototype.isPrototypeOf()
代替instanceof
,但是其实不是的见下面“自定义instanceof
行为”。综上:只是
instanceof
内部逻辑利(OrdinaryHasInstance
)和Object.prototype.isPrototypeOf()
存在相似的地方。二、
instanceof check
要弄清原因还是看下规范InstanceofOperator :
即:
constructorFunc
不是对象,直接抛TypeError
异常;constructorFunc
定义了Symbol.hasInstance
方法(不为undefined
就算),则调用该方法,并以该方法的返回值作为instanceof
的值;OrdinaryHasInstance(target, V)
流程。三、自定义
instanceof
行为instanceof
操作符默认通过原型链判断(OrdinaryHasInstance
),但可以利用Symbol.hasInstance
自定义instanceof
行为。所有函数(包含不可以作为构造函数的函数,如
Function.prototype
)都定义了Symbol.hasInstance
方法。四、利用
Object.getPrototypeOf
实现instanceof
参考
The text was updated successfully, but these errors were encountered: