DIV CSS 佈局教程網

typeof 與 instanceof 的缺陷與優化方案
編輯:關於JavaScript     

typeof 與 instanceof 是常見的型別判斷方式,但兩者都有無法精確辨識物件子類型的限制。本文說明其原理,並提供以 toString 為基礎的優化做法。

typeof

typeof 會回傳字串,用來表示運算元的型別。它適合判斷基本型別,但對陣列、日期與自訂物件通常只回傳 object。

typeof 100;
typeof 'onepixel';
typeof true;
typeof {};
typeof [];
typeof new Date();
typeof parseInt;

instanceof

instanceof 用來判斷物件是否為某個建構函式的實例。它會沿著原型鏈檢查,因此 [] instanceof Object 也會是 true。

[] instanceof Array;
[] instanceof Object;
new Date() instanceof Date;
new Date() instanceof Object;

由於 Array、Date 等物件都繼承自 Object,單靠 instanceof 無法區分具體子類型。

優化方案

可借用 Object.prototype.toString 取得物件的內部標籤,再映射成型別名稱。這種方式能較準確辨識 Array、Date、RegExp 等型別。

var class2type = {};

var typeList = 'Boolean Number String Function Array Date RegExp Object Error Symbol'.split(' ');

typeList.forEach(function (item) {
  class2type['[object ' + item + ']'] = item.toLowerCase();
});

function getObjType(obj) {
  if (obj === null) {
    return obj + '';
  }

  if (typeof obj === 'object') {
    return class2type[Object.prototype.toString.call(obj)] || 'object';
  }

  if (typeof obj === 'function') {
    return class2type[Object.prototype.toString.call(obj)] || 'function';
  }

  return typeof obj;
}

此做法比單用 typeof 或 instanceof 更適合需要精確型別判斷的情境。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved