【JavaScript】精准判断内置对象和自定义对象类型

232 阅读1分钟

内置的typeof判断对象的类型不太准确。因为其返回值只有:'string', 'number', 'boolean', 'undefined', 'symbol', 'bigint', 'object', 'function'。可以利用Object.prototype.toString.call来获取内置对象真实类型(但不能获取自定义类型);用constructor.name 获取自定义类型。

function myTypeof(o) {
  if (o === null) return "null";
  if (typeof o !== "object") return typeof o;
  else {
    const typeStr = Object.prototype.toString.call(o);
    const type = typeStr.slice(8, -1).toLocaleLowerCase();
    // 判断自定义类型
    if (!globalThis[typeStr]) {
      return o.constructor.name
    }
    return type
  }
}

function Foo() {}
console.log(myTypeof(new Foo)) // Foo