【前端面试】instanceof原理

9,770 阅读1分钟

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__;
    }
}

推荐博客:

(1)js中的instanceof运算符

(2)今日头条面试总结——instanceof原理

(3)javascript中原型链与instanceof原理