判断一个实例是否属于某种类型
let person = function(){
}
let no = new person();
no instanceof person; // true
在了解原理及手撸代码之前,需要了解JS原型链: JS原型链
1、 主要实现原理: 只要右边变量的prototype在左边变量的原型链上即可
2、
function new_instanceOf(leftValue, rightValue) {
let rightValue = rightValue.prototype; // 取右表达式的prototyoe值
leftValue = leftValue.__proto__;
while (true) {
if (leftValue === rightProto) {
return true;
}
if (leftValue === null) {
return false;
}
leftVaule = leftVaule.__proto__ ;
}
}
function instance_of(l,r) {
let rProto = r.prototype;
let lValue = l.__proto__;
while(true) {
if (lValue === null) {
return false;
}
if (lValue === rProto) {
return true;
}
lValue = lValue.__proto__;
}
}
// 开始测试
var a = []
var b = {}
function Foo(){}
var c = new Foo()
function child(){}
function father(){}
child.prototype = new father()
var d = new child()
console.log(instance_of(a, Array)) // true
console.log(instance_of(b, Object)) // true
console.log(instance_of(b, Array)) // false
console.log(instance_of(a, Object)) // true
console.log(instance_of(c, Foo)) // true
console.log(instance_of(d, child)) // true
console.log(instance_of(d, father)) // true