型別判斷是 JavaScript 面試與日常開發的必考題。typeof 看起來簡單,卻有許多反直覺的地方;instanceof 則涉及原型鏈。本文把兩者放在一起梳理,並附上七道經典智力測驗。
typeof 是一個一元運算子,放在運算數前面使用,無論運算數是什麼型別都可以,回傳值必定是字串。它可能回傳的結果只有:number、boolean、string、function、object、undefined,以及 ES6 之後新增的 symbol。
實務上一個很有價值的用法是偵測變數是否存在:
if (typeof a !== "undefined") {
alert("ok");
}
這裡之所以不能直接寫 if (a),是因為當 a 從未宣告過時,直接讀取會丟出 ReferenceError,而 typeof 對未宣告的識別字不會報錯。
| 資料型別 | typeof 回傳 |
|---|---|
| Undefined | "undefined" |
| Null | "object" |
| 布林值 | "boolean" |
| 數值 | "number" |
| 字串 | "string" |
| Symbol(ES6) | "symbol" |
| 函式物件 | "function" |
| 任何其他物件 | "object" |
| 宿主物件(由執行環境提供) | 依實作而定 |
幾個容易誤解的例子:
typeof NaN === 'number'; // NaN 雖是 "Not-A-Number",型別仍是 number
typeof new Number(1) === 'object'; // 加了 new 就變成包裝物件
typeof [1, 2, 4] === 'object'; // 陣列也是 object
typeof new Date() === 'object'; // 日期也是 object
typeof function(){} === 'function'; // 函式是唯一能被分辨出來的 object
問題就在這裡:陣列、正則、日期、錯誤物件,typeof 一律回 "object",根本無法區分。
要精確判斷,標準做法是借用 Object.prototype.toString,它會回傳形如 "[object Array]" 的字串:
| 資料 | toString | typeof |
|---|---|---|
| "foo" | String | string |
| new String("foo") | String | object |
| new Number(1.2) | Number | object |
| true | Boolean | boolean |
| new Date() | Date | object |
| new Error() | Error | object |
| [1, 2, 3] | Array | object |
| /abc/g | RegExp | object |
var type = Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
這行小技巧可以取出型別名稱,是很多型別檢查工具庫的底層依據。ES5.1 之後也可以用 Array.isArray 專門判斷陣列。
// 1
var y = 1, x = y = typeof x; x;
// 2
(function f(f){ return typeof f(); })(function(){ return 1; });
// 3
var foo = { bar: function() { return this.baz; }, baz: 1 };
(function(){ return typeof arguments[0](); })(foo.bar);
// 4
var foo = { bar: function(){ return this.baz; }, baz: 1 };
typeof (f = foo.bar)();
// 5
var f = (function f(){ return "1"; }, function g(){ return 2; })();
typeof f;
// 6
var x = 1;
if (function f(){}) { x += typeof f; }
x;
// 7
(function(foo){ return typeof foo.bar; })({ foo: { bar: 1 } });
答案依序是:"undefined"、"number"、"undefined"、"undefined"、"number"、"1undefined"、"undefined"。
第一題考變數提升。表達式由右往左求值,x 此時已宣告但尚未賦值,其值為 undefined,typeof 得到 "undefined" 字串,於是 y 與 x 都被指派成這個字串。
第二題只是要你看清 f 與 f() 的差別。傳入的參數是函式本身,呼叫後回傳 1,typeof 1 自然是 "number"。
第三題考 this 指向。this 永遠指向函式被執行時的上下文,而非定義時的位置(箭頭函式除外)。foo.bar 被當成獨立函式傳入並透過 arguments[0]() 呼叫,this 已指向全域物件,foo 上的 baz 取不到,結果是 "undefined"。
第四題同理,(f = foo.bar)() 也是脫離物件被呼叫,this 依舊不是 foo。
第五題出現了少見的分組運算子(逗號運算子)。括號內以逗號串接多個運算式,整個分組的值取最後一個:
var a = (1, 2, 3);
document.write(a); // 3
所以 f 得到的是 2,typeof 為 "number"。
第六題涉及規範上的灰色地帶。在 if 條件中寫函式宣告,語法上會被當成表達式求值,條件為真,但引擎並不會真的把 f 宣告到作用域中,因此 typeof f 是 "undefined",字串拼接後得到 "1undefined"。
第七題純粹考細心。傳入的實參是 { foo: { bar: 1 } } 整體,形參 foo 指向它,foo.bar 是 { bar: 1 } 這個物件,typeof 為 "undefined"。
instanceof 用來判斷某個建構函式的 prototype 屬性,是否出現在被檢測物件的原型鏈上。
var a = new Array();
a instanceof Array; // true
a instanceof Object; // true,因為 Array 繼承自 Object
function test(){}
var b = new test();
b instanceof test; // true
一個常被忽略的事實:arguments 看起來很像陣列,但它不是陣列。
(function(){ return arguments instanceof Array; })(); // false
再看一組更完整的例子:
function C(){}
function D(){}
var o = new C();
o instanceof C; // true
o instanceof D; // false,D.prototype 不在 o 的原型鏈上
o instanceof Object; // true
C.prototype = {}; // 重新指派 prototype
var o2 = new C();
o2 instanceof C; // true
o instanceof C; // false,舊的 C.prototype 已不在 o 的原型鏈上
D.prototype = new C(); // 原型繼承
var o3 = new D();
o3 instanceof D; // true
o3 instanceof C; // true
function f(){ return f; }
new f() instanceof f; // false
function g(){}
new g() instanceof g; // true
差別在於 f 在函式本體中把 f 自己當成回傳值,而 this 的運作讓 f.prototype 被覆寫或不再對應到新物件的原型鏈上;g 則是標準的空建構函式。實務上,只要你在建立物件後重新指派了 constructor 的 prototype,instanceof 的結果就會跟直覺不同,這也是為什麼很多類別繼承的實作會特別處理 prototype 的還原。