typeof 和 instanceof 运算符区别?

1、前置

js 是种弱类型语言,对变量的类型没有限制。例如,如果我们使用字符串类型创建了一个变量,后面又可以为同一变量分配一个数字:

let message = 'Hello'; // 分配一个字符串
message = 14; // 分配一个数字

优点:这种动态性为我们提供了灵活性并简化了变量声明。
确点:我们永远不能确保变量包含某种类型的值。 例如,以下函数greet(who)需要一个字符串参数,但是,我们可以使用任何类型的参数来调用该函数:

function greet(who) {
  return `Hello, ${who}!`
}

greet('World'); // => 'Hello, World!'
// You can use any type as argument
greet(true);    // => 'Hello, true!'
greet([1]);     // => 'Hello, 1!'

2、typeof 主要用来检测基础数据类型

  • ECMAScript 有 6 种简单数据类型(也称为原始类型):String 、Number、Boolean、Symbol和 Undefined、Null、
  • 还有一种复杂数据类型叫 Object(对象:函数、数组等等)

typeof是用于确定 expression 类型的运算符:

const typeAsString = typeof expression;

expression 的计算结果是我们要查找的类型的值。 expression 可以是变量myvariable,属性访问器myObject.myProp,函数调用myFunction()或数字 14。

typeof expression,取决于expression的值,结果可能为:
'string', 'number', 'boolean', 'symbol', 'undefined', 'object', 'function'。

我们来看看typeof运算符每种类型的情况:

2.1 常规类型

A) String:
const message = 'hello!';
typeof message; // => 'string'
B) Number:

const number = 5;
typeof number; // => 'number'

typeof NaN;    // => 'number'
C) Boolean:

const ok = true;
typeof ok; // => 'boolean'
D) Symbol:

const symbol = Symbol('key');
typeof symbol; // => 'symbol'
E) undefined:

const nothing = undefined;
typeof nothing; // => 'undefined'

2.2 Object and function

F) Objects:

const object = { name: 'Batman' };
typeof object; // => 'object'

const array = [1, 4, 5];
typeof array; // => 'object'

const regExp = /Hi/;
typeof regExp; // => 'object'
G) Functions:

function greet(who) {
  return `Hello, ${who}!`
}

typeof greet; // => 'function'

2.3 typeof null

如上我们看到的,用 typeof 判断对象结果是 'object'。

但是,typeof null也会计算为'object'!

const missingObject = null;
typeof missingObject; // => 'object'

typeof nullobject是 JS 初始实现中的一个错误。

因此,在使用typeof检测对象时,需要另外检查null:

function isObject(object) {
  return typeof object === 'object' && object !== null;
}

isObject({ name: 'Batman' }); // => true
isObject(15);                 // => false
isObject(null);               // => false

2.4 typeof 和未定义的变量

虽然typeof expression通常决定于expression的类型,但也可以使用typeof来确定是否定义了变量。

// notDefinedvar is not defined
notDefinedVar; // throws ReferenceError

typeof有一个不错的属性,当typeof评估未定义变量的类型时,不会引发 ReferenceError 错误:

// notDefinedVar is not defined
typeof notDefinedVar; // => 'undefined'

变量notDefinedVar没有在当前作用域内定义。然而,typeof notDefinedVar不会抛出引用错误,而是将结果计算为 'undefined'。

我们可以使用typeof来检测是否未定义变量,如果typeof myVar === 'undefined' 为 true, 则 myVar 未定义。

3、instanceof 主要用来检测实例类型(Object)

console.log(person instanceof Object); // 变量 person 是 Object 吗?
console.log(colors instanceof Array); // 变量 colors 是 Array 吗?
console.log(pattern instanceof RegExp); // 变量 pattern 是 RegExp 吗?
  • 使用 JS 函数的通常方法是通过在其名称后添加一对括号来调用它:
function greet(who) {
  return `Hello, ${who}!`;
}

greet('World'); // => 'Hello, World!'

greet('World')是常规函数调用。

  • JS 函数可以做更多的事情:它们甚至可以构造对象! 要使函数构造对象,只需在常规函数调用之前使用new关键字:
function Greeter(who) {
  this.message = `Hello, ${who}!`;
}

const worldGreeter = new Greeter('World');
worldGreeter.message; // => 'Hello, World!'

new Greeter('World')是创建实例worldGreeter的构造函数调用。

  • 如何检查 JS 是否使用特定构造函数创建了特定实例? 使用 instanceof 运算符:
const bool = object instanceof Constructor;

其中object是对对象求值的表达式,而Constructor是构造对象的类或函数,instanceof计算为布尔值。

worldGreeter实例是使用Greeter构造函数创建的,因此worldGreeter instanceof Greeter计算结果为true

  • 从ES6 开始,可以使用 class 来定义对象。例如,定义一个类Pet,然后创建它的一个实例myPet:
class Pet {
  constructor(name) {
    this.name = name;
  }
}

const myPet = new Pet('Lily');
new Pet('Lily')是创建实例myPet的构造调用。

由于myPet是使用Pet类构造的-const myPet = new Pet('Lily'), 所以 myPet instanceof Pet 的结果为 true:

myPet instanceof Pet; // => true

但是,普通对象不是Pet的实例:

const plainPet = { name: 'Zoe' };
plainPet instanceof Pet; // => false

我们发现instanceof对于确定内置的特殊实例(如正则表达式、数组)很有用:

function isRegExp(value) {
  return value instanceof RegExp;
}
isRegExp(/Hello/); // => true
isRegExp('Hello'); // => false

function isArray(value) {
  return value instanceof Array;
}
isArray([1, 2, 3]); // => true
isArray({ prop: 'Val' }); // => false
  • instanceof 和父类
    现在,Cat 扩展了父类Pet:
class Cat extends Pet {
  constructor(name, color) {
    super(name);
    this.color = color;
  }
}

const myCat = new Cat('Callie', 'red');

不出所料,myCat是Cat类的实例:

myCat instanceof Pet; // => true

但同时,myCat也是基类Pet的一个实例:

myCat instanceof Pet; // => true

posted @ 2022-02-24 10:55  Daeeman  阅读(50)  评论(0编辑  收藏  举报