TypeOf And InstanceOf
本篇介紹關於TypeOf
和 InstanceOf
資料來源:Jartto's blog-JS基礎|搞懂 typeof 和 instanceof
Both:
能避免程式碼異常,為一種較嚴謹的處理方式。
TypeOf:
用於判斷參數是什麼類型的方法。
console.log(typeof 123); //number
console.log(typeof 'jartto'); //string
console.log(typeof !!'0'); //boolean
console.log(typeof new Function()); //function
console.log(typeof name); //undefined
但也要注意暫時性死區的問題
console.log(typeof x);
let x;
較適用於基本類型的數據
不適用於物件、陣列、null 的判斷
InstanceOf:
instanceof
用來判斷 A 是否為 B 的實例,表達式為A instanceof B
,如果「是」返 回true
,否則返回false
。有點A是不是B的概念。但是是物件、陣列型的。
[] instanceof Array ; //true
({}) instanceof Object ; //true
new Date () instanceof Date ; //true
擴展:
分析 [ ]、Array、Obj 的關係(或者說順序)
從
instanceof
先判斷出
[].__proto__
指向Array.prototype
再來判斷
Array.prototype.__proto__
又指向Obj.prototype
最終判斷
Obj.prototype.__proto__
指向了null
原型鏈結束。
圖示說明-1:
資料來源:__proto__ Vs. prototype in JS

b.__proto__
指向Foo.prototype
Foo.prototype.__proto__
指向Object.prototype
圖示說明-2:
這邊說明prototype
與__proto__
的先後順序
資料來源:JS必須知道的繼承prototype

function FOO(){...}
只會產出FOO.prototype
var foo = new FOO();
後就會產出foo.__proto__
More Explained:
Last updated
Was this helpful?