Daily-Question icon indicating copy to clipboard operation
Daily-Question copied to clipboard

【Q453】typeof 与 instanceof 的区别

Open shfshanyue opened this issue 4 years ago • 5 comments

shfshanyue avatar Dec 30 '20 04:12 shfshanyue

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

如以下示例:

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

shfshanyue avatar Dec 30 '20 04:12 shfshanyue

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

> typeof null
"object"

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

知识来源: JavaScript 忍者秘籍

ghost avatar May 25 '21 10:05 ghost

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

> typeof null
"object"

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

知识来源: JavaScript 忍者秘籍

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

shfshanyue avatar May 25 '21 14:05 shfshanyue

我不管你问什么 我就做题

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

Vi-jay avatar May 14 '22 04:05 Vi-jay

instanceof 的结果可以通过修改 [Symbol.toStringTag] 属性影响

xiaochena avatar Apr 16 '24 04:04 xiaochena