掌握instanceof原理,面试无忧

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;
}
}获取更多资料QQ群786276452

猜你喜欢

转载自blog.csdn.net/web_god/article/details/82855847