類型檢查:typeof 和 instanceof 運算符區別?

做者:Dmitri Pavlutin
譯者:前端小智
來源:Dmitri Pavlutin
點贊再看,微信搜索 【大遷世界】關注這個沒有大廠背景,但有着一股向上積極心態人。本文 GitHub https://github.com/qq44924588... 上已經收錄,文章的已分類,也整理了不少個人文檔,和教程資料。**

最近開源了一個 Vue 組件,還不夠完善,歡迎你們來一塊兒完善它,也但願你們能給個 star 支持一下,謝謝各位了。javascript

github 地址:https://github.com/qq44924588...前端

智米們確定知道,JS 是種弱類型語言,對變量的類型沒有限制。vue

例如,若是咱們使用字符串類型建立了一個變量,後面又能夠爲同一變量分配一個數字:java

let message = 'Hello'; // 分配一個字符串

message = 14; // 分配一個數字

這種動態性爲咱們提供了靈活性並簡化了變量聲明。git

很差方面,咱們永遠不能確保變量包含某種類型的值。 例如,如下函數greet(who)須要一個字符串參數,可是,咱們能夠使用任何類型的參數來調用該函數:github

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!'

有時咱們須要在 JS 中檢查變量的類型,要怎麼作?正則表達式

使用typeof運算符以及instanceof來檢查實例類型。express

1.typeof運算符

在 JS 中,基本類型有 StringNumberBooleanSymbol 等。此外,還有函數、對象和特殊值undefinednull數組

typeof是用於肯定 expression 類型的運算符:微信

const typeAsString = typeof expression;

expression 的計算結果是咱們要查找的類型的值。 expression 能夠是變量myVariable,屬性訪問器myObject.myProp,函數調用myFunction()或數字 14

typeof expression,取決於expression的值,結果可能爲:'string''number''boolean''symbol''undefined''object''function'

咱們來看看typeof運算符每種類型的狀況:

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 判斷對象結果是 'object'

可是,typeof null也會計算爲'object'

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

typeof null'object'是 JS 初始實現中的一個錯誤。

所以,在使用typeof檢測對象時,須要另外檢查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來肯定是否認義了變量。

// 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 未定義。

2. instanceof 運算符

使用 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

2.1 instanceof 和父類

如今,Cat 擴展了父類Pet

class Cat extends Pet {
  constructor(name, color) {
    super(name);
    this.color = color;
  }
}

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

不出所料,myCatCat類的實例:

myCat instanceof Pet; // => true

但同時,myCat也是基類Pet的一個實例:

myCat instanceof Pet; // => true

3. 總結

JS 是一種弱類型的語言,這意味着對變量的類型沒有限制。

typeof expression能夠用來查看 expression 的類型,結果是多是其中的一個:'string''number''boolean', 'symbol''undefined''object''function'

typeof null的值爲'object',所以使用typeof檢測對象的正確方法是typeof object ==='object'&& object!== null

instanceof運算符讓咱們肯定實例的構造函數。 若是objectConstructor的實例,則object instanceof Constructortrue


代碼部署後可能存在的BUG無法實時知道,過後爲了解決這些BUG,花了大量的時間進行log 調試,這邊順便給你們推薦一個好用的BUG監控工具 Fundebug

原文:https://dmitripavlutin.com/ja...

交流

文章每週持續更新,能夠微信搜索【大遷世界 】第一時間閱讀,回覆【福利】有多份前端視頻等着你,本文 GitHub https://github.com/qq449245884/xiaozhi 已經收錄,歡迎Star。

相關文章
相關標籤/搜索