instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。 语法:object instanceof constructor 描述:instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。
instanceof 运算符可以准确判断引用类型数据,判断不了基本类型数据。
console.log({} instanceof Object) // true
console.log([] instanceof Array) // true
console.log(function() {} instanceof Function) // true
console.log(1 instanceof Number) // false
实现:
function instance_of(L, R) {
var O = R.prototype
L = L.__proto__
while(true) {
if(L === null)
return false;
if(O === L)
return true;
L = L.__proto__;
}
}
// L表示对象实例,R表示构造函数或者父类型实例
// 取R的显式原型,取L的隐式原型
// 循环遍历,进行判断R和L的原型是否一致,一致则返回true,不一致则继续查找L的原型链
function Person() {}
var p = new Person()
console.log(instance_of(p,Person)) // true
console.log(instance_of({},Object)) // true