zoukankan      html  css  js  c++  java
  • typeof 与 instanceof 检测数据类型的区别(进阶)

    本篇文只涉及到ES5的数据类型

    原始数据类型:String  Number Boolean Null  Undefined

    复杂数据类型:Object Function Array 

      typeof: 返回的对应的数据类型

      console.log(typeof(undefined));  // undefined

      console.log(typeof(null)); // object  为什么不是 null

      在检测null 的时候会检测出null 的机器码后三位都为000,因此返回 null

      理解: typeof 返回的 数据类型是根据机器码01011的后三位来定的  000的机器码返回的就是 => object

                  null 的数据存储在机器码中是 000000。。。。。0000  根据后三位存储的是000 而返回 object

                  也可以理解为 js 的设计bug

      console.log(typeof([])); // object

      console.log({}); // object

      console.log(new Date()); // object

      console.log(typeof(function(){})) ; // function

      console.log(typeof Array); // function  为什么不是 object

          在检测function的时候,本应该返回的是object,但是object 分为两类,会判断其内部有无call 方法,而function是有call 的方法的,所以返回 function;

      理解: typeof 在检测复杂数据的时候应该返回的是 object, 但是又分为两种 object=> object function

                 js 的设计中在引用数据类型(复杂数据)的内部定义了一个方法 [ [ call ] ];

                 typeof 在检测过程中会首先判断数据类型上有无call 方法,有的话返回 funciton, 没有的话返回 object

     typeof 面试题:

       var str = "zp";

       console.log(typeof(str)); // string

       var str = new String("zp"); // 实例后的对象

       console.log(str); // String {"zp"} 会已key value的形式保存

       console.log(typeof(str)); // object

      总结: typeof 检测数据类型的时候 少null  多function

    instanceof : 检测返回的boolean => true 或者 false

      a instanceof b 表示 a 是否是 b 实例化构造出来的,a 是否为 b 的实例对象。原型 原型链

      console.log([].instanceof Array); // true

      console.log(new Date() instanceof Date); // true

      function Person() {};

      console.log(new Person() instanceof Person);  // true

      console.log([] instanceof Object); // true

      console.log(new Date() instanceof Object); // true

      console.log(new Person() instanceof Object); // true

      理解:

        instanceof 通过检测原型链来判断,如果说 a instanceof b 返回true, 并且 b instanceof c 也返回true, 也就会 a instanceof c 也返回true。

    typeof 和 instanceOf 其他解决检测数据类型的方法:

     object.prototype.toString.call("1"); // "[object String]"

    区别:

      typeof 返回的字符串,该字符串表示的是该数据的类型, 少null多object

      instanceof 是判断a 是否为b 的实例对象,检测的是原型和原型链

  • 相关阅读:
    HGOI20191115 模拟赛 题解
    HGOI20191114 CSP模拟赛 反思
    HGOI 20191108 题解
    HGOI 20191107 题解
    HGOI 20191106 题解
    HGOI 20191105 题解
    HGOI 20191103am 题解
    HGOI 20191101am 题解
    HGOI 20191031am 题解
    新的博客!!!
  • 原文地址:https://www.cnblogs.com/PengZhao-Mr/p/14534229.html
Copyright © 2011-2022 走看看