Geek-James/Blog

6.彻底搞懂instance和typeOf

Geek-James opened this issue · 0 comments

概述

instanceof运算符用来判断一个构造函数的prototype属性所指向的对象是否存在另外一个要检测对象的原型链上

描述

instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。

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 不适合检测一个对象本身的类型

instanceof 检测一个对象A是不是另一个对象的实例原理:

查看对象B的prototype指向的对象是否在对象A的[[prototype]]链上.如果在,则返回true,如果不在则返回false,特殊情况,当对象的prototype为null将会报错.

函数模拟A instanceof B

function _instanceof(A,B) {
    var o = B.protrotype; // 取B的显示原型
    A = A.__proto__; //取A的隐式原型
    while(true) {
        // Object.prototype.__proto__ === null
        // 一直沿着原型链往上查找
        if(A === null) {
            return false;
        }
        if (o === A) {
            return true;
        }
        A = A.__proto__;
    }
    
}


总结:

1.所有的构造器的 constructor 都指向 Function

2.Function 的 prototype 指向一个特殊匿名函数,而这个特殊匿名函数的 proto 指向 Object.prototype