高级前端
js
【Q453】typeof 与 instanceof 的区别

typeof 与 instanceof 的区别

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 461 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

  1. typeof 用以判断基础数据类型 (null 除外)
  2. instanceOf 借助原型链判断复杂数据类型

如以下示例:

> typeof 3
< "number"
> [] instanceof Array
< true

typeof 能够准确检查除了 null 之外的基础数据类型(number, string, symbol, bigInt, undefined, boolean, null)

> typeof null
"object"

instanceof 的语义是检查操作符右边的函数原型是否存在于左边对象的原型链中

知识来源: JavaScript 忍者秘籍 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

typeof 能够准确检查除了 null 之外的基础数据类型(number, string, symbol, bingInt, undefined, boolean, null)

> typeof null
"object"

instanceof 的语义是检查操作符右边的函数原型是否存在于左边对象的原型链中

知识来源: JavaScript 忍者秘籍 (opens in a new tab)

@liweinandever 真是学习了,今天我才注意到 bigint 也是基本数据类型,见文档 Primitive (opens in a new tab),另外你这里的 bigint 有个 typoerror

Author 回答者: Vi-jay (opens in a new tab)

我不管你问什么 我就做题

function myInstanceof(obj, clazz) {
  let proto = Object.getPrototypeOf(obj);
  while (proto && proto !== clazz.prototype) {
    proto = Object.getPrototypeOf(proto);
  }
  return !!proto;
}