基础文之-----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>
复制代码

 

posted @   糖~豆豆  阅读(198)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
Live2D
欢迎阅读『基础文之-----typeof 和 instanceof』
点击右上角即可分享
微信分享提示