JavaScript 的型別判斷向來是討論不完的話題,因為它沒有完美的單一方法。以下把常見的幾種方式、各自的盲點整理清楚。
最實用的場合是「檢查某個變數是否存在」。直接寫 if (haorooms != undefined) 在變數未宣告時會丟出 ReferenceError:
if (haorooms != undefined) { } // Uncaught ReferenceError
if (typeof haorooms != undefined) { } // 不會報錯
注意第二行其實也有 bug——typeof 回傳的是字串,應該比對 "undefined":
if (typeof haorooms !== "undefined") { }
型別判斷的結果如下:
typeof "string"; // "string"
typeof 1; // "number"
typeof false; // "boolean"
typeof undefined; // "undefined"
typeof Symbol(); // "symbol"
typeof function(){}; // "function"
typeof null; // "object" ← 歷史遗留的 bug
typeof []; // "object"
typeof {}; // "object"
可見除了基本型別與 function 之外,null、陣列、物件全都回傳 "object"。typeof null === "object" 是 JavaScript 早期設計留下的錯誤,因為無法修正而保留至今。
[] instanceof Array; // true
它檢查的是原型鏈上是否存在該建構式的 prototype,因此自訂類別也能用。但缺點是無法跨 iframe 判斷(不同 window 的 Array 建構式不同),且基本型別一律回傳 false。
[].constructor === Array; // true
({}).constructor === Object; // true
"string".constructor === String; // true
(123).constructor === Number; // true
true.constructor === Boolean; // true
function employee(name, job, born){
this.name = name; this.job = job; this.born = born;
}
var haorooms = new employee("Bill Gates", "Engineer", 1985);
haorooms.constructor; // function employee(...)
它能拿到實際的建構式,但這個屬性可以被覆寫,可靠性不如 toString。
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(NaN); // "[object Number]"
Object.prototype.toString.call(function(){}); // "[object Function]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
這是最可靠的方式,因為它讀的是每個物件的 [[Class]] 內部屬性,無法被一般程式碼偽造。唯一限制是自訂類別一律顯示 [object Object]。
$.isWindow(window); // true
// 實作原理
isWindow: function( obj ) {
return obj != null && obj == obj.window;
}
所以只要偽造一個自指的物件就能騙過它:
var fakeWindow = {};
fakeWindow.window = fakeWindow;
$.isWindow(fakeWindow); // true
這也說明了為什麼「看起來能用」的判斷式往往有漏洞。
要判斷「是不是陣列」,最準確的現代寫法是 Array.isArray();判斷物件用 typeof x === 'object' && x !== null;需要區分各種內建型別時用 Object.prototype.toString.call(x)。至於 isPrototypeOf 這類方法則屬於進階用法,日常較少用到。
JavaScript 是個歷史包袱很重的語言,同一件事往往有五種寫法。理解每種方法的邊界,比記住某一種寫法更重要。