instanceof操作符与原型链

今天在复习小红书原型链内容的时候 关于instanceof操作符产生了疑惑。

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

比如  A instanceof B  就是看 B.prototype 是否存在与A的原型链上(是否在A.__proto__.__proto__.__proto__......(n))

    function SuperType() {
        this.property = true
    }
    SuperType.prototype.getSuperValue = function () {
        return this.property
    }
    function SubType() {
        this.subproperty = false
    }
    SubType.prototype = new SuperType()
    SubType.prototype.getSubValue = function () {
        return this.subproperty
    }
    var instance = new SubType()
    console.log(instance instanceof Object)               //true
    console.log(instance instanceof SuperType)             //true
    console.log(instance instanceof SubType)                //true

小红书中关于原型链有这么一段代码,那么根据原型链可以看下面的图片

只需要判断 B.prototype 是否在A的原型链上就可以。

来看下面的代码

Function(A) instanceof Function(B)

Function(B).prototype === Function(A).__proto__

所以 返回true

Function instanceof Object

Object.prototype === Function.__proto__.__proto__

所以返回 true

Object instanceof Object

Object.prototype === Object.__proto__.proto__

下面附上一章原型链图 帮助理解

另外还有一个isPrototypeOf()方法 可以确定原型链之间的关系

用isPrototypeOf检查原型链如下代码

    Object.prototype.isPrototypeOf(instance)            //true
    SubType.prototype.isPrototypeOf(instance)           //true
    SuperType.prototype.isPrototypeOf(instance)         //true

 

posted @ 2018-03-06 17:11  就是咩咩羊呀  阅读(118)  评论(0编辑  收藏  举报