JavaScript 有五種基本型別(Undefined、Null、Boolean、Number、String)與一種複雜型別 Object,而 Object 底下又細分出 Array、Function、Date、RegExp 等具體類型。問題是:要怎麼準確判斷一個變數到底屬於哪一種?坊間流傳的方法不少,準確度卻各異。
先準備一批測試變數,涵蓋實務上常見的各種情況:
var num = 123;
var str = 'abcdef';
var bool = true;
var arr = [1, 2, 3, 4];
var json = { name: 'wenzi', age: 25 };
var func = function () { console.log('this is function'); };
var und = undefined;
var nul = null;
var date = new Date();
var reg = /^[a-zA-Z]{5,20}$/;
var error = new Error();
最常用的方法。實測結果:
console.log(typeof num, typeof str, typeof bool, typeof arr, typeof json,
typeof func, typeof und, typeof nul, typeof date, typeof reg, typeof error);
// number string boolean object object function undefined object object object object
結論很直白:只有 number、string、boolean、function、undefined 能被正確判斷。arr、json、nul、date、reg、error 統統回報 object。也就是說,typeof 既分不出陣列與物件,也分不出 null。
typeof 對所有參考型別都回傳 object,為了解決這個問題,ECMAScript 引入了 instanceof。它與 typeof 相似,但要求你明確指定要確認的類型:
function Person() {}
var Tom = new Person();
console.log(Tom instanceof Person); // true
更實用的是它能沿著原型鏈向上檢查,因此多層繼承也判斷得出來:
function Person() {}
function Student() {}
Student.prototype = new Person();
var John = new Student();
console.log(John instanceof Student); // true
console.log(John instanceof Person); // true
拿來測前面那批變數:
console.log(num instanceof Number, str instanceof String, bool instanceof Boolean,
arr instanceof Array, json instanceof Object, func instanceof Function,
und instanceof Object, nul instanceof Object, date instanceof Date,
reg instanceof RegExp, error instanceof Error);
// num : false
// str : false
// bool : false
// arr : true
// json : true
// func : true
// und : false
// nul : false
// date : true
// reg : true
// error : true
num、str、bool 都判斷不出來。這是因為它們是基本型別的「值」,而不是物件;若改用建構式包裝,就能判斷了:
var num = new Number(123);
var str = new String('abcdef');
var boolean = new Boolean(true);
另外要注意 und 與 nul 之所以在 instanceof Object 下回傳 false,是因為 JavaScript 並沒有名為 Undefined 或 Null 的全域建構函式可用來比對。
constructor 本來是原型物件上的屬性,指向建構函式。由於實例查找屬性時會沿原型鏈上溯,因此實例也能存取它。
先看看 num.constructor 長什麼樣:
function Number() { [native code] }
既然它指向 Number,那麼 num.constructor == Number 就能作為判斷依據,其他型別同理:
function Person() {}
var Tom = new Person();
// undefined 與 null 沒有 constructor 屬性
console.log(Tom.constructor == Person, num.constructor == Number,
str.constructor == String, bool.constructor == Boolean,
arr.constructor == Array, json.constructor == Object,
func.constructor == Function, date.constructor == Date,
reg.constructor == RegExp, error.constructor == Error);
// 全部為 true
除了 undefined 與 null,其餘型別都能判斷出來。但這個方法有兩個罩門。
罩門一:constructor 可以被改寫。
function Person() {}
function Student() {}
Student.prototype = new Person(); // 原型被換掉,constructor 也一起變了
var John = new Student();
console.log(John.constructor == Student); // false
console.log(John.constructor == Person); // true
罩門二:跨 frame 會失效。假設父頁面有一個 iframe,子頁面中宣告了一個陣列並傳給父頁面,父頁面用 arr.constructor == Array 判斷會得到 false。原因有兩點:陣列屬參考型資料,傳遞的只是引用位址;而每個頁面的 Array 原生物件位址各自獨立,子頁面的陣列對應的是子頁面的 Array 建構函式。這個坑很難追蹤,務必留意。
先看它怎麼用:
console.log( Object.prototype.toString.call(num), Object.prototype.toString.call(str), Object.prototype.toString.call(bool), Object.prototype.toString.call(arr), Object.prototype.toString.call(json), Object.prototype.toString.call(func), Object.prototype.toString.call(und), Object.prototype.toString.call(nul), Object.prototype.toString.call(date), Object.prototype.toString.call(reg), Object.prototype.toString.call(error) ); // '[object Number]' '[object String]' '[object Boolean]' '[object Array]' '[object Object]' // '[object Function]' '[object Undefined]' '[object Null]' '[object Date]' '[object RegExp]' '[object Error]'
全部型別都判斷出來了,包含 undefined 與 null。要用的時候取出後面的型別名稱即可,例如:
Object.prototype.toString.call(arr) == "[object Array]"; // 判斷是否為陣列
它為什麼這麼可靠?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 Array]" 這樣的字串。配合 call 借用這個方法,就能取得任何物件的 [[Class]],把型別判斷轉化為字串比較。這也是它跨 frame 仍然有效的原因——[[Class]] 是每個物件自身的標記,與頁面無關。
jQuery 提供了 $.type:
console.log($.type(num), $.type(str), $.type(bool), $.type(arr), $.type(json),
$.type(func), $.type(und), $.type(nul), $.type(date), $.type(reg), $.type(error));
// number string boolean array object function undefined null date regexp error
看起來很熟悉對吧?它就是 Object.prototype.toString.call() 結果的第二個參數。來看看 jQuery(2.1.2)內部怎麼實作:
var class2type = {};
var toString = class2type.toString;
type: function (obj) {
if (obj == null) {
return obj + "";
}
// Support: Android<4.0, iOS<6 (functionish RegExp)
return (typeof obj === "object" || typeof obj === "function")
? (class2type[toString.call(obj)] || "object")
: typeof obj;
},
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),
function (i, name) {
class2type["[object " + name + "]"] = name.toLowerCase();
});
先執行 jQuery.each 那段,class2type 會變成一份對照表:
class2type = {
'[object Boolean]' : 'boolean',
'[object Number]' : 'number',
'[object String]' : 'string',
'[object Function]': 'function',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object RegExp]' : 'regExp',
'[object Object]' : 'object',
'[object Error]' : 'error'
}
再來看 type 方法的邏輯:
type: function (obj) {
// 若傳入 null 或 undefined,直接回傳其字串形式
if (obj == null) {
return obj + "";
}
// 低版本 Android/iOS 的 functionish RegExp 會被 typeof 判為 function,這裡一併處理
// 若 typeof 結果是 object 或 function,查表取得型別名稱,查不到就回傳 "object"
// 其餘型別直接用 typeof 的結果
return (typeof obj === "object" || typeof obj === "function")
? (class2type[toString.call(obj)] || "object")
: typeof obj;
}
至此就很清楚:$.type 本質上就是 Object.prototype.toString.call 加上一張字串對照表,把 "[object Boolean]" 轉成 'boolean'。查表查不到時退回 "object";而 number、string、boolean 這三類根本不是物件,直接交給 typeof 處理即可。
型別 typeof instanceof constructor toString.call $.type
num number false true [object Number] number
str string false true [object String] string
bool boolean false true [object Boolean] boolean
arr object true true [object Array] array
json object true true [object Object] object
func function true true [object Function] function
und undefined false - [object Undefined] undefined
nul object false - [object Null] null
date object true true [object Date] date
reg object true true [object RegExp] regexp
error object true true [object Error] error
優點 簡單直接 能判斷複雜型別 幾乎涵蓋全部型別 涵蓋全部型別 -
缺點 可判斷型別少 基本型別無效 不能跨 iframe 需字串比較 IE6 下 undefined/null 皆為 Object
且不能跨 iframe 且 constructor 易遭竄改
日常業務中,判斷基本型別用 typeof 就夠;判斷自訂類別的繼承關係用 instanceof;需要一個可靠且跨 frame 的通用判斷,Object.prototype.toString.call 是最佳選擇——這也是 jQuery 與眾多工具庫的實作基礎。理解它的原理,比記住任何單一寫法都更有價值。