1、js中的instanceof运算符
instanceof运算符用来判断一个构造函数的prototype属性所指向的对象是否存在另外一个要检测对象的原型链上
2、语法
obj instanceof Object; //Object的构造函数是否存在于obj的原型链上
3、描述
instanceof 运算符用来检测 constructor.prototype 是否存在于参数 obj 的原型链上。
4、实例
(1)instanceof的普通的用法,obj instanceof Object 检测Object.prototype是否存在于参数obj的原型链上。
以下示例展示:Person的原型在p的原型链中
functionPerson(){};
var p =new Person();
console.log(p instanceof Person);//true
(2)继承中判断实例是否属于它的父类
以下示例展示:Student和Person都在s的原型链中
functionPerson(){};
functionStudent(){};
var p =new Person();
Student.prototype=p; //继承原型
var s=new Student();
console.log(s instanceof Student);//true
console.log(s instanceof Person);//true
总结:
对应上述规范做个函数模拟A instanceof B:
function_instanceof(A, B){
var O = B.prototype;// 取B的显示原型
A = A.__proto__;// 取A的隐式原型
while (true) {
Object.prototype.__proto__ === null
if (A === null)
return false;
if (O === A) // 这里重点:当 O 严格等于 A 时,返回 true
return true;
A = A.__proto__;
}
}