typeof 和 instanceof 判断类型对象

  • typeof : 适用于判断基本类型、方法对象等。判断所有对象,都返回对象[Object, Object]
  • instanceof : 适用于判断对象(Object)。判断对象比较详细
  1. typeof 操作符:
  • 优点:
    • typeof 可以用来判断基本数据类型和函数类型。
    • 使用简单,对于基本数据类型和函数,都可以直接使用 typeof 进行判断。
  • 缺点:
    • 对于引用数据类型(如数组、对象等),使用 typeof 则无法准确区分其具体的子类型。
    • 对于 null 类型,使用 typeof 返回的是 “object”,这可能会导致混淆。

示例使用:

1
2
3
4
5
6
7
console.log(typeof 42); // 输出: "number"  
console.log(typeof "hello"); // 输出: "string"
console.log(typeof true); // 输出: "boolean"
console.log(typeof undefined); // 输出: "undefined"
console.log(typeof null); // 注意:输出为"object",这是 typeof 的一个缺陷
console.log(typeof {}); // 输出: "object"
console.log(typeof []); // 输出: "object"(数组也被判断为 object)
  1. instanceof 操作符:
  • 优点:
    • 可以准确地判断对象的具体子类型。
    • 对自定义构造函数创建的实例进行检查时非常有用。
  • 缺点:
    • 如果在多个框架或窗口间传递对象,则可能出现问题。因为每个窗口/框架都有自己独立的全局执行环境和相应的构造函数。

示例使用:

1
2
3
4
5
6
7
8
9
10
function Car(make, model) {  
this.make = make;
this.model = model;
}

let car = new Car('Toyota', 'Corolla');
console.log(car instanceof Car) ;// true

let myString = new String('Hello');
console.log(myString instanceof String);// true