JS进阶系列 --- typeof&instanceof

JavaScript 中 typeof 和 instanceof 常用来判断一个变量是否为空,或者是什么类型的
typeof用于判断值类型,instanceof用于判断引用类型

typeof

语法:typeof type
参数:type(要检测的类型)

typeof 一般只能返回如下几个结果:”number”、”string”、”boolean”、”object”、”function” 和 “undefined”。

console.log(typeof 111); //number
console.log(typeof '111'); //string
console.log(typeof undefined); //undefined
console.log(typeof true);      //boolean   
console.log(typeof NaN);       //number
console.log(typeof null);      //object
console.log(typeof new Function()); //function
console.log(typeof new Object()); //object
console.log(typeof Function); //function
console.log(typeof Object); //function

instanceof

语法:object instanceof constructor
参数:object(要检测的对象.)constructor(某个构造函数)
原理:instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。

在理解instanceof之前,你需要学会原型的相关知识。
请参考我的另一篇博客:JS进阶系列 — 原型

    function Animal(){

    }
    Animal.typename = '动物';
    Animal.prototype.sleep = function(){
        console.log('Animal can sleep');
    }
    function Dog(){

    }
    Dog.typename = '狗';
    Dog.prototype = new Animal();
    Dog.prototype.bark = function(){
        console.log('Dog can bark');
    }
    let dog = new Dog();
    //以下为true
    console.log(dog instanceof Dog);
    console.log(dog instanceof Animal);
    console.log(dog instanceof Object);
    //以下为false
    console.log(Dog instanceof Animal)

如何理解这段代码呢?
A instanceof B 返回的是 A是不是继承于B的
沿着A的原型链一直往上找,如果找到了B则返回true,如果到顶了还没找到则返回false

dog instanceof Dog
找到了dog.__proto__ == Dog.prototype 返回true
dog instanceof Animal
找到了dog.__proto__.__proto__(等价于Dog.prototype.__proto__) == Animal.prototype 返回true
dog instanceof Object
找到了dog.__proto__.__proto__.__proto__(等价于Animal.prototype.__proto__) == Object.prototype 返回true

Dog instanceof Animal
Dog.__proto__为Function.prototype 不等于 Animal.prototype,返回false

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值