参考来源)
console.log(typeof 0); // number
console.log(typeof BigInt(Number.MAX_SAFE_INTEGER)); // bigint
console.log(typeof '0'); // string
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof function () { }); // function
console.log(typeof Symbol); // function
console.log(typeof Symbol()); // symbol
console.log(typeof Date); // function
console.log(typeof Date()); // string
console.log(typeof new Date); // object
console.log(typeof new Date()); // object
console.log(typeof RegExp); // function
console.log(typeof RegExp()); // object
console.log(typeof new RegExp); // object
console.log(typeof new RegExp()); // object
console.log(typeof []); // object
console.log(typeof {}); // object
console.log(typeof null); // object
如果我们想判断一个对象的正确类型,可以考虑使用 instanceof,因为内部机制是通过 判断实例对象的 __proto__ 和生成该实例的构造函数的 prototype 是不是引用的同一个地址(也就是原型链的方式)来判断的。
错误
在 ECMAScript 2015 之前,typeof 总能保证对任何所给的操作数返回一个字符串。即便是没有声明的标识符,typeof 也能返回 'undefined'。使用 typeof 永远不会抛出错误。
但在加入了块级作用域的 let 和 const 之后,在其被声明之前对块中的 let 和 const 变量使用 typeof 会抛出一个 ReferenceError。块作用域变量在块的头部处于“暂存死区”,直至其被初始化,在这期间,访问变量将会引发错误。
typeof undeclaredVariable === 'undefined';
typeof newLetVariable; // ReferenceError
typeof newConstVariable; // ReferenceError
typeof newClass; // ReferenceError
let newLetVariable;
const newConstVariable = 'hello';
class newClass{};
instanceof
instanceof 运算符用于检测构造函数 prototype 属性是否出现在某个实例对象的原型链上。可以用来判断都属于 Object 类型和一些特殊情况的对象,如:数组和对象,但不能用于基础数据类型。
语法
object instanceof constructor
参数
object 某个实例对象
constructor 某个构造函数
描述
instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。
示例
B instanceof A:判断 B 是否为 A 的实例,可以用于继承关系中