js中instanceof详解

instanceof运算符用于检测对象的原型链上是否存在构造函数的 prototype属性,即是否存在构造函数的原型对象prototype;有则返回 true,否则返回 false

语法: 对象 instanceof 构造函数

看如下代码

	  function ClassA(arg) {
        this.arg = arg
      }
      ClassA.prototype.x = 20
      function ClassB(x) {
        this.x = x
      }
      ClassB.prototype = new ClassA(30)
      function ClassC(y) {
        this.y = y
      }
      ClassC.prototype = new ClassB(100)
      var a = new ClassA('xxxxx'),
        b = new ClassB(40),
        c = new ClassC(100)
      // instanceof 运算符用来检测一个对象在其原型链中是否存在一个构造函数的prototype属性。
      console.log(a instanceof Object) // true
      console.log(a instanceof ClassA) // true
      console.log(b instanceof Object) // true
      console.log(b instanceof ClassB) // true
      console.log(b instanceof ClassA) // true
      console.log(c instanceof ClassA) // true
      console.log(c instanceof ClassB) // true
      console.log(c instanceof ClassC) // true
      console.log(c instanceof Object) // true

可以看到上面输出的全是true,这是为什么呢?先回顾一下 instanceof 运算符:instanceof运算符用于检测对象的原型链上是否存在构造函数的 prototype属性,有则返回 true,否则返回 false;既然说到了原型链,那我们就把实例对象 a,b,c 的原型链给写出来,如下图

  • 实例对象a
    在这里插入图片描述

由上图可以看出在实例对象 a 的原型链上存在两个构造函数的prototype属性,依据 instanceof 的定义,所以 a instanceof Object a instanceof ClassA 都为true

  • 实例对象b
    在这里插入图片描述
    实例对象b有点特殊,因为其构造函数的原型对象prototype又指向了ClassA构造函数的实例对象(ClassB.prototype = new ClassA(30)),所以此时ClassB的原型对象prototype就是ClassA构造函数的实例对象,即ClassB.prototype.__proto__指向了ClassA.prototype;
    由上图可以看出实例对象b的原型链上存在三个构造函数的prototype属性,依据 instanceof 的定义,所以 b instanceof Object
    b instanceof ClassA b instanceof ClassB 都为true
  • 实例对象c

在这里插入图片描述同理,c instanceof ClassA c instanceof ClassB c instanceof ClassC c instanceof Object 都为true

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值