為什麼要用 Object.prototype.toString,而不是 Function.prototype.toString 或其他?這與它們的 toString 實作方式有關。ECMA 對 Object.prototype.toString 的說明如下:
Object.prototype.toString( ) When the toString method is called, the following steps are taken: 1. Get the [[Class]] property of this object. 2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]”. 3. Return Result (2)
流程說穿了很簡單:先取得物件的內部 [[Class]] 屬性(也就是它的型別標記),再把 "[object"、型別名、" ]" 三段字串拼起來回傳。
而 ECMA 對 Array 的定義中寫著:
The [[Class]] property of the newly constructed object is set to “Array”.
因此我們可以用下面的方式檢測陣列:
function isArray(o) { return Object.prototype.toString.call(o) === '[object Array]'; }
這種做法同時解決了 instanceof 的跨頁面(跨 iframe)問題——不同 window 下的 Array 建構函式不是同一個,instanceof 會誤判——也避免了 duck typing 屬性檢測方式的漏洞,算是相當漂亮的解法。
除此之外,同樣的手法也能用來判斷 Date、Function、RegExp 等其他型別。
另外常見的寫法還有:
var arr = []; return arr instanceof Array;
以及直接比對 constructor:
return o.constructor == Array;
三者各有取捨:constructor 可能被自行改寫而失真,instanceof 有跨 frame 問題,而 Object.prototype.toString.call() 在正確性上最穩妥。ES5.1 之後有了原生的 Array.isArray(),若執行環境允許,優先用它。