typeof 和 instanceof的区别?

2024-07-20 14:58:59 161
`typeof` 和 `instanceof` 是 JavaScript 中用于检查数据类型的两种不同方法,它们的作用和使用场景各有不同。以下是对它们的详细说明:

typeof

  • 作用:返回一个字符串,表示未经计算的操作数的类型。
  • 适用对象:可以对原始类型和函数使用,对于对象类型会返回 "object"
  • 返回值
    • "undefined":表示值未定义。
    • "boolean":表示布尔值。
    • "number":表示数字。
    • "bigint":表示大整数(ES2020)。
    • "string":表示字符串。
    • "symbol":表示符号(ES6)。
    • "function":表示函数。
    • "object":表示对象(包括数组、null等)。

示例:

console.log(typeof 42);            // "number"
console.log(typeof 'hello');       // "string"
console.log(typeof true);          // "boolean"
console.log(typeof undefined);     // "undefined"
console.log(typeof Symbol());      // "symbol"
console.log(typeof 10n);           // "bigint"
console.log(typeof function() {}); // "function"
console.log(typeof {});            // "object"
console.log(typeof []);            // "object"
console.log(typeof null);          // "object" // null 是特殊情况

instanceof

  • 作用:检查一个对象是否是某个构造函数的实例。
  • 适用对象:主要用于对象类型检查,检测对象的原型链是否包含构造函数的 prototype
  • 返回值:布尔值,truefalse

示例:

function Person() {}
let alice = new Person();

console.log(alice instanceof Person); // true
console.log(alice instanceof Object); // true

let arr = [];
console.log(arr instanceof Array);    // true
console.log(arr instanceof Object);   // true

区别

  1. 检测范围

    • typeof:可以用于检测所有原始类型和函数,但对于对象类型返回 "object",无法进一步区分具体类型。
    • instanceof:只能用于检测对象类型,检查对象是否是某个构造函数的实例。
  2. 返回类型

    • typeof:返回一个表示类型的字符串。
    • instanceof:返回一个布尔值。
  3. 具体用途

    • typeof:适用于简单类型检查,尤其是原始类型(如数字、字符串、布尔值等)。
    • instanceof:适用于对象类型检查,尤其是在需要判断对象是否是某个类或构造函数的实例时。

使用场景

  1. typeof 使用场景
    • 检查变量是否已定义。
    • 检查原始类型。
    • 检查函数类型。

示例:

let value;
if (typeof value === 'undefined') {
    console.log('value is undefined');
}

if (typeof value === 'number') {
    console.log('value is a number');
}

if (typeof value === 'function') {
    console.log('value is a function');
}
  1. instanceof 使用场景
    • 判断对象是否是某个类的实例。
    • 检查对象的继承关系。

示例:

class Animal {}
class Dog extends Animal {}

let myDog = new Dog();

if (myDog instanceof Dog) {
    console.log('myDog is an instance of Dog');
}

if (myDog instanceof Animal) {
    console.log('myDog is an instance of Animal');
}

if (myDog instanceof Object) {
    console.log('myDog is an instance of Object');
}

总结

  • typeof:适用于检查原始类型、函数类型等,返回类型字符串。对于对象类型,只能返回 "object",无法区分具体对象类型。
  • instanceof:适用于检查对象类型和继承关系,返回布尔值。只能用于对象,不适用于原始类型。

理解 typeofinstanceof 的区别和使用场景,可以更好地进行类型检查和调试,提高代码的健壮性和可维护性。