已知基于 instanceof 可以实现检测:实例是否属于某个类,现在需要自己编写这样的一个方法,实现出 instanceof 的效果
//=>example:要检测的实例
//=>classFunc:要检测的类
function instance_of(example, classFunc) {
//...
}
let res = instance_of([12,23],Array);
console.log(res); //=>true
如果example实例的原型链里面有一条链最终是可以指向classFunc类的原型,[12,23] 数组的__proto__能够指向Array.prototype.。
function instance_of(example,classFunc){
let classprototype = classFunc.portotype;
proto = example.__proto__;
while(true){
if(proto===null){
//已经到了object.prototype.__proto__
return flase;
}
if(proto===classprototype){
//在当前实例的原型链上找到了当前类
return true ;
}
proto=proto.__proto__;
}
}
//IE不支持此方法
可以使用getPrototypeOf找原型,控制台可以输入Object.getPrototypeOf(Object.getPrototypeOf(/$/))去查看它所属的属性和方法。
function instance_of(example,classFunc){
let classprototype = classFunc.portotype;
proto = Object.getPrototypeOf(example);
while(true){
if(proto===null){
//已经到了object.prototype.__proto__
//或者Object.getPrototypeOf(Object.getPrototype)===null
return flase;
}
if(proto===classprototype){
//在当前实例的原型链上找到了当前类
return true ;
}
proto=Object.getPrototypeOf(proto);
}
}
在函数的原型上有Symbol.hasInstance方法的,处理的原理和instanceof一样的。
Function.prototype : Symbol . hasInstance
console.log( [ ] instanceof Array );
//浏览器内部其实是基于Symbol . hasInstance 检测的
cosole . log(Array [Symbol.hasInstance ] ( [ ] ) );