型別判斷是 JavaScript 裡看似簡單、細節卻很多的課題。常用的手段有四種:typeof、instanceof、constructor 與 prototype,各有適用範圍與陷阱。
先準備幾個待測變數:
var a = "iamstring.";
var b = 222;
var c = [1,2,3];
var d = new Date();
var e = function () { alert(111); };
var f = function () { this.name = "22"; };
typeof a // "string" typeof b // "number" typeof c // "object" typeof d // "object" typeof e // "function" typeof f // "function"
最常見的做法。注意它回傳的是字串,所以比較時右邊要打引號:
typeof a == "string" // true typeof a == String // false
typeof 的強項是判斷 function 與基本型別,弱點是遇到陣列、日期、自訂物件時一律回 "object",無從分辨。(另外 typeof null 回 "object",這是語言本身的歷史遺留。)
c instanceof Array // true d instanceof Date // true f instanceof Function // true f instanceof function // false
它沿原型鏈向上檢查,因此能應付繼承情境。注意右側必須是建構函式且大小寫不能錯,寫成 function(小寫關鍵字)會直接報錯。
c.constructor == Array // true d.constructor == Date // true e.constructor == Function // true
constructor 的問題出在繼承。當原型鏈被改寫,constructor 會指向錯誤的類:
function A() {}
function B() {}
A.prototype = new B(); // A 繼承自 B
var aObj = new A();
aObj.constructor === B // true,但其實應該是 A
aObj.constructor === A // false
instanceof 不會有這個困擾,無論直接或間接繼承都會回 true:
aObj instanceof B // true aObj instanceof A // true
修法是在改寫原型之後手動把 constructor 指回自己:
A.prototype = new B(); A.prototype.constructor = A; aObj.constructor === A // true aObj.constructor === B // false
Object.prototype.toString.call(a) === '[object String]' // true Object.prototype.toString.call(b) === '[object Number]' // true Object.prototype.toString.call(c) === '[object Array]' // true Object.prototype.toString.call(d) === '[object Date]' // true Object.prototype.toString.call(e) === '[object Function]' // true
寫法繁瑣、字串大小寫也不能出錯,但它是最通用、最可靠的方式,連 cross-realm 的物件(例如 iframe 裡建立的陣列)都能正確辨識。
日常判斷基本型別用 typeof 就夠了;已知大方向是某類物件時,用 instanceof 最簡潔;需要萬無一失的通用判斷,就用 Object.prototype.toString.call()。