zoukankan      html  css  js  c++  java
  • 基础文之-----typeof 和 instanceof

    为了巩固基础,我会通过实例来详细说明,让我们一起搞懂 typeof 和 instanceof。

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
    </head>
    <body>
      <script>
      console.log(   'typeof 123', ':', typeof 123   ); 
      // number
      console.log(   "typeof 'str'", ':', typeof 'str'   );
      // string
      console.log(   "typeof !'0'", ':', typeof !'0'   );
      // boolean
      console.log(   "typeof new Function()", ':', typeof new Function()   );
      // function
      console.log(   'typeof myname', ':', typeof myname   );
      // undefined
      console.log(   'typeof null', ':', typeof null   );
      // object
      console.log(   "typeof {name: 'hello'}", ':', typeof {name: 'hello'}   );
      // object
      console.log(   "typeof [1,2,3]", ':', typeof [1,2,3]   );
      // object
      console.log(   "[1,2] instanceof Array", ':', [1,2] instanceof Array   );
      // true
      console.log(   "Array.isArray([1,2])", ':', Array.isArray([1,2])  );
      // true
      console.log(   "({name: 'he'}) instanceof Object", ':', ({name: 'he'}) instanceof Object   );
      // true
      console.log(   "new Date() instanceof Date", ':', new Date() instanceof Date   );
      function Person(){}
      console.log(    new Person() instanceof Person   );
      // true
      // 接下來是繼承
      function Parent(){};
      function Child(){};
      function Other(){};
      Child.prototype = new Parent();
      let child = new Child();
      console.log(   child instanceof Child   ); // true
      console.log(   child instanceof Parent   ); // true
      console.log(   child instanceof Object   ); // true
      console.log(   child instanceof Other   ); // false
      console.log(   Parent.prototype.__proto__ === Object.prototype   ); // true
      // instanceof 只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类型。
      function fun() {}
    console.log(typeof fun); // function
    console.log(fun instanceof Function); // true
    console.log(fun instanceof Object); // true
    
      </script>
    </body>
    </html>

  • 相关阅读:
    python 基础第二篇
    python 基础第五篇
    python 基础第四篇
    购物小编程(完整编码)
    计算机 python概论
    str 相关操作
    python 基础第三篇
    Nginx 配置多站点vhost
    h5页面宽度设置7.5rem
    js 倒计时,转义
  • 原文地址:https://www.cnblogs.com/sugartang/p/12461356.html
Copyright © 2011-2022 走看看