類型檢查:typeof 和 instanceof 運(yùn)算符區(qū)別?
智米們肯定知道,JS 是種弱類型語(yǔ)言,對(duì)變量的類型沒(méi)有限制。
例如,如果我們使用字符串類型創(chuàng)建了一個(gè)變量,后面又可以為同一變量分配一個(gè)數(shù)字:
- let message = 'Hello'; // 分配一個(gè)字符串
- message = 14; // 分配一個(gè)數(shù)字
這種動(dòng)態(tài)性為我們提供了靈活性并簡(jiǎn)化了變量聲明。
不好方面,我們永遠(yuǎn)不能確保變量包含某種類型的值。例如,以下函數(shù)greet(who)需要一個(gè)字符串參數(shù),但是,我們可以使用任何類型的參數(shù)來(lái)調(diào)用該函數(shù):
- 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!'
有時(shí)我們需要在 JS 中檢查變量的類型,要怎么做?
使用typeof運(yùn)算符以及instanceof來(lái)檢查實(shí)例類型。
1. typeof運(yùn)算符
在 JS 中,基本類型有 String、Number、Boolean和 Symbol 等。此外,還有函數(shù)、對(duì)象和特殊值undefined和null。
typeof是用于確定 expression 類型的運(yùn)算符:
- const typeAsString = typeof expression;
expression 的計(jì)算結(jié)果是我們要查找的類型的值。expression 可以是變量myVariable,屬性訪問(wèn)器myObject.myProp,函數(shù)調(diào)用myFunction()或數(shù)字 14。
typeof expression,取決于expression的值,結(jié)果可能為:'string', 'number', 'boolean', 'symbol', 'undefined', 'object', 'function'。
我們來(lái)看看typeof運(yùn)算符每種類型的情況:
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'
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'
1.1 typeof null
如上我們看到的,用 typeof 判斷對(duì)象結(jié)果是 'object'。
但是,typeof null也會(huì)計(jì)算為'object'!
- const missingObject = null;
- typeof missingObject; // => 'object'
typeof null為'object'是 JS 初始實(shí)現(xiàn)中的一個(gè)錯(cuò)誤。
因此,在使用typeof檢測(cè)對(duì)象時(shí),需要另外檢查null:
- function isObject(object) {
- return typeof object === 'object' && object !== null;
- }
- isObject({ name: 'Batman' }); // => true
- isObject(15); // => false
- isObject(null); // => false
1.2 typeof 和未定義的變量
雖然typeof expression通常決定于expression的類型,但也可以使用typeof來(lái)確定是否定義了變量。
- // notDefinedVar is not defined
- notDefinedVar; // throws ReferenceError
typeof有一個(gè)不錯(cuò)的屬性,當(dāng)typeof評(píng)估未定義變量的類型時(shí),不會(huì)引發(fā) ReferenceError 錯(cuò)誤:
- // notDefinedVar is not defined
- typeof notDefinedVar; // => 'undefined'
變量notDefinedVar沒(méi)有在當(dāng)前作用域內(nèi)定義。然而,typeof notDefinedVar不會(huì)拋出引用錯(cuò)誤,而是將結(jié)果計(jì)算為 'undefined'。
我們可以使用typeof來(lái)檢測(cè)是否未定義變量,如果typeof myVar === 'undefined' 為 true, 則 myVar 未定義。
2. instanceof 運(yùn)算符
使用 JS 函數(shù)的通常方法是通過(guò)在其名稱后添加一對(duì)括號(hào)來(lái)調(diào)用它:
- function greet(who) {
- return `Hello, ${who}!`;
- }
- greet('World'); // => 'Hello, World!'
greet('World')是常規(guī)函數(shù)調(diào)用。
JS 函數(shù)可以做更多的事情:它們甚至可以構(gòu)造對(duì)象!要使函數(shù)構(gòu)造對(duì)象,只需在常規(guī)函數(shù)調(diào)用之前使用new關(guān)鍵字:
- function Greeter(who) {
- this.message = `Hello, ${who}!`;
- }
- const worldGreeter = new Greeter('World');
- worldGreeter.message; // => 'Hello, World!'
new Greeter('World')是創(chuàng)建實(shí)例worldGreeter的構(gòu)造函數(shù)調(diào)用。
如何檢查 JS 是否使用特定構(gòu)造函數(shù)創(chuàng)建了特定實(shí)例?使用 instanceof 運(yùn)算符:
- const bool = object instanceof Constructor;
其中object是對(duì)對(duì)象求值的表達(dá)式,而Constructor是構(gòu)造對(duì)象的類或函數(shù),instanceof計(jì)算為布爾值。
worldGreeter實(shí)例是使用Greeter構(gòu)造函數(shù)創(chuàng)建的,因此worldGreeter instanceof Greeter計(jì)算結(jié)果為true。
從ES6 開(kāi)始,可以使用 class 來(lái)定義對(duì)象。例如,定義一個(gè)類Pet,然后創(chuàng)建它的一個(gè)實(shí)例myPet:
- class Pet {
- constructor(name) {
- this.name = name;
- }
- }
- const myPet = new Pet('Lily');
new Pet('Lily')是創(chuàng)建實(shí)例myPet的構(gòu)造調(diào)用。
由于myPet是使用Pet類構(gòu)造的-const myPet = new Pet('Lily'), 所以 myPet instanceof Pet 的結(jié)果為 true:
- myPet instanceof Pet; // => true
但是,普通對(duì)象不是Pet的實(shí)例:
- const plainPet = { name: 'Zoe' };
- plainPet instanceof Pet; // => false
我們發(fā)現(xiàn)instanceof對(duì)于確定內(nèi)置的特殊實(shí)例(如正則表達(dá)式、數(shù)組)很有用:
- 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
2.1 instanceof 和父類
現(xiàn)在,Cat 擴(kuò)展了父類Pet:
- class Cat extends Pet {
- constructor(name, color) {
- super(name);
- this.color = color;
- }
- }
- const myCat = new Cat('Callie', 'red');
不出所料,myCat是Cat類的實(shí)例:
- myCat instanceof Pet; // => true
但同時(shí),myCat也是基類Pet的一個(gè)實(shí)例:
- myCat instanceof Pet; // => true
3. 總結(jié)
JS 是一種弱類型的語(yǔ)言,這意味著對(duì)變量的類型沒(méi)有限制。
typeof expression可以用來(lái)查看 expression 的類型,結(jié)果是可能是其中的一個(gè):'string', 'number', 'boolean', 'symbol', 'undefined', 'object', 'function'。
typeof null的值為'object',因此使用typeof檢測(cè)對(duì)象的正確方法是typeof object ==='object'&& object!== null。
instanceof運(yùn)算符讓我們確定實(shí)例的構(gòu)造函數(shù)。如果object是Constructor的實(shí)例,則object instanceof Constructor為true。
本文轉(zhuǎn)載自微信公眾號(hào)「大遷世界」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系大遷世界公眾號(hào)。