寫 JavaScript 時,typeof 和 instanceof 幾乎是必用的兩個運算子,但也幾乎是每個人都抱怨過的兩個運算子。社群裡流傳的一句話說得很直白:這兩個運算子可能是 JavaScript 最大的設計缺陷,因為你幾乎不可能從它們身上拿到想要的結果。
typeof 會回傳一個表示運算式型別的字串,可能的值包括 number、boolean、string、object、undefined、function。看定義似乎沒問題,實際用起來卻很快出現落差:
var a = 1; console.log(typeof a); // "number" var b = new Number(1); console.log(typeof b); // "object"
同樣是數字,用字面值建立的回報 number,用建構式建立的卻回報 object。既然如此,typeof 對「這個變數到底是不是 Number」這個問題,其實答不出令人滿意的答案。
每個值內部都有一個 [[Class]] 屬性,記錄它真正的型別。要讀取它,可以借用 Object.prototype 上的 toString:
var a = 1; var b = new Number(1); console.log(Object.prototype.toString.call(a)); // [object Number] console.log(Object.prototype.toString.call(b)); // [object Number]
字串固定是 [object Xxx] 的形式,中間那段就是型別名稱。用 slice 把前後綴切掉,就能得到乾淨的結果:
console.log(Object.prototype.toString.call(a).slice(8, -1)); // Number console.log(Object.prototype.toString.call(b).slice(8, -1)); // Number
把上面的邏輯包成一個函式,就能同時處理字面值與建構式建立的物件:
function is(obj, type) {
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
}
拿幾組變數對照看看差異:
var a1 = 1, a2 = Number(1);
var b1 = "hello", b2 = new String("hello");
var c1 = [1, 2, 3], c2 = new Array(1, 2, 3);
console.log(typeof a1); // number
console.log(typeof a2); // object
console.log(typeof b1); // string
console.log(typeof b2); // object
console.log(typeof c1); // object
console.log(typeof c2); // object
console.log(is(a1, "Number")); // true
console.log(is(a2, "Number")); // true
console.log(is(b1, "String")); // true
console.log(is(b2, "String")); // true
console.log(is(c1, "Array")); // true
console.log(is(c2, "Array")); // true
不論用哪一種方式建立,is() 都能給出一致且正確的判斷。至於 typeof,它並非毫無用處——最實用的場合是判斷一個變數是否已定義或已賦值,例如 typeof x !== 'undefined'。
instanceof 用來判斷物件是否為某型別的實例,但碰到內建型別時同樣力不從心:
console.log("abc" instanceof String); // false
console.log("abc" instanceof Object); // false
console.log(new String("abc") instanceof String); // true
console.log(new String("abc") instanceof Object); // true
字面前後差異懸殊,原因是原始型別值並不是物件,自然談不上原型鏈。只有在比較自訂的建構函式時,instanceof 才能準確反映繼承關係:
function Person() {}
function Man() {}
Man.prototype = new Person();
console.log(new Man() instanceof Man); // true
console.log(new Man() instanceof Person); // true
實務上的結論很清楚:需要精確的型別名稱時,用 Object.prototype.toString;需要判斷繼承鏈時,用 instanceof;而 typeof 留給「是否已定義」這類簡單檢查即可。