1,instanceof 的作用是用来做检测类型:
(1)instanceof 可以检测某个对象是不是另一个对象的实例;
- var Person = function() {};
- var student = new Person();
- console.log(student instanceof Person); // true
复制代码
(2)instanceof 可以检测父类型;
- function Person() {};
- function Student() {};
- var p = new Person();
- Student.prototype=p; // 继承原型
- var s=new Student();
- console.log(s instanceof Student); //true
- console.log(s instanceof Person); //true
复制代码
但是, instanceof 不适合检测一个对象本身的类型.
2,instanceof 检测一个对象 A 是不是另一个对象 B 的实例的原理:
查看对象 B 的 prototype 指向的对象是否在对象 A 的 [[prototype]] 链上. 如果在, 则返回 true, 如果不在则返回 false. 不过有一个特殊的情况, 当对象 B 的 prototype 为 null 将会报错(类似于空指针异常).
函数模拟 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__;
- }
- }
来源: https://juejin.im/post/5b7f64be51882542c83476f0