在JavaScript中typeof和instanceof運算子都可以進行型別檢查,那麼它們之間有什麼差異?本篇文章為大家介紹typeof和instanceof操作符的差別。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有幫助。

相關推薦:《javascript影片教學》
智米們肯定知道,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!'
有時我們需要在JS 中檢查變數的類型,怎麼做?
使用typeof運算子以及instanceof來檢查實例類型。
1.<span style="font-size: 18px;">typeof</span>#運算子
在JS 中,基本型別有String、Number、Boolean和Symbol 等。此外,還有函數、物件和特殊值undefined和null。
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');
不出所料,myCat是Cat类的实例:
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运算符让我们确定实例的构造函数。 如果object是Constructor的实例,则object instanceof Constructor为true。
原文地址:https://dmitripavlutin.com/javascript-typeof-instanceof/
作者:Dmitri Pavlutin
译文地址:https://segmentfault.com/a/1190000038312457
更多编程相关知识,请访问:编程课程!!
以上是JavaScript中類型檢查:typeof和instanceof操作符的區別的詳細內容。更多資訊請關注PHP中文網其他相關文章!