DIV CSS 佈局教程網

JavaScript 對象類型判斷的幾種方式與取捨
編輯:JavaScript基礎知識     

撰寫 JavaScript 時經常需要判斷「這是一個什麼型別的物件」——例如寫一個工具函數,要依參數型別走不同分支。可用的手段有 typeof、instanceof,以及更可靠的 Object.prototype.toString,各有邊界。

一、typeof:簡單但不足夠

<script type="text/javascript">
var object = {};
var b = true;
alert(typeof object + " " + typeof b);
</script>

那麼 null 與 undefined 呢?

alert(typeof null + " " + typeof undefined);

typeof null 竟回傳 "object"(這與直覺不符,但符合規範),typeof undefined 回傳 "undefined"。所以使用 typeof 判斷物件型別時要特別小心:對方有可能是 null。

下面是 typeof 作用於常見型別的結果(可自行驗證):

問題顯而易見:Array、Date、RegExp 全都顯示為 object,無法區分。

二、instanceof:能判斷引用型別

var now = new Date();
var pattern = /^[\s\S]*$/;
var names = ['zq', 'john'];

alert((now instanceof Date) + " "
    + (pattern instanceof RegExp) + " "
    + (names instanceof Array));

instanceof 能正確判斷這些引用型別,但它無法處理基本型別,而且在跨 frame 的場景下會失效。

跨 frame 的失效場景

main.html:

<!doctype html>
<html lang="en">
<head>
  <title>Main</title>
</head>
<frameset cols="45%,*">
  <frame name="frame1" src="frame1.html"/>
  <frame name="frame2" src="frame2.html"/>
</frameset>
</html>

frame1.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>frame1</title>
</head>
<script type="text/javascript">
  var names = ['riccio zhang', 'zq', 'john'];
</script>
<body style="background: #ccc"></body>
</html>

frame2.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>frame2</title>
  <script type="text/javascript">
    document.write("top.frame1.names instanceof Array: "
      + (top.frame1.names instanceof Array));
    document.write("<br/>");
    document.write("top.frame1.names instanceof top.frame1.Array: "
      + (top.frame1.names instanceof top.frame1.Array));
    document.write("<br/>");
    document.write("top.frame1.Array === top.frame2.Array? "
      + (top.frame1.Array === top.frame2.Array));
  </script>
</head>
<body style="background: #747474"></body>
</html>

names 是在 frame1 中由 frame1 的 Array 建立的。把它拿去和 frame2 的 Array 比,結果自然是 false——兩者根本不是同一個建構函數。第三個輸出也證實了這一點:frame1 與 frame2 各自擁有獨立的 Array。顯然,我們不可能每次都手動指定對應 frame 的建構函數來比對。

三、Object.prototype.toString:最通用的方案

var toString = {}.toString;
var now = new Date();
alert(toString.call(now));   // [object Date]

{}.toString 取得的是 Object 上的 toString 方法,toString.call(now) 則是借用這個方法來執行。它會回傳形如 [object Class] 的字串——Date 得到 [object Date],陣列得到 [object Array]。既然型別資訊直接寫在字串裡,只要比對這個字串就能精確判斷型別,而且不受 frame 影響。

由此可以封裝一個工具模組:

tools.js:

var tools = (function (undefined) {

  var class2type = {},
      toString = {}.toString;

  var fun = {

    // 回傳小寫的實際型別名稱
    type: function (obj) {
      return obj === null || obj === undefined
        ? String(obj)
        : class2type[toString.call(obj)];
    },

    isArray: function (obj) {
      return fun.type(obj) === "array";
    },

    isFunction: function (obj) {
      return fun.type(obj) === "function";
    },

    each: function (arr, callback) {
      var i = 0,
          hasLength = arr.length ? true : false;
      if (!callback || (typeof callback !== 'function') || !hasLength) {
        return;
      }
      for (i = 0; i < arr.length; i++) {
        if (callback.call(arr[i], i, arr[i]) === false) {
          break;
        }
      }
    }
  };

  // 建立 [object Xxx] → xxx 的對映表
  fun.each("Boolean Number String Array Date RegExp Object Function".split(" "),
    function (i, name) {
      class2type["[object " + name + "]"] = name.toLowerCase();
    });

  return fun;
})();

type 接受一個參數,以小寫形式回傳實際型別;isArray、isFunction 則是常用的語法糖。需要更多判斷時,往 class2type 對映表補一條即可。

改寫前面的 frame2 例子:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>frame2</title>
  <script type="text/javascript" src="tools.js"></script>
  <script type="text/javascript">
    document.write("top.frame1.names instanceof Array: "
      + (top.frame1.names instanceof Array));
    document.write("<br/>");
    document.write("top.frame1.names instanceof top.frame1.Array: "
      + (top.frame1.names instanceof top.frame1.Array));
    document.write("<br/>");
    document.write("top.frame1.Array === top.frame2.Array? "
      + (top.frame1.Array === top.frame2.Array));
    document.write("<br/>");
    document.write("tools.isArray(top.frame1.names)? "
      + tools.isArray(top.frame1.names));
  </script>
</head>
<body style="background: #747474"></body>
</html>

前兩種方式都返回 false,而 tools.isArray 正確辨識了跨 frame 的陣列。

四、方法選擇建議

  • 判斷 undefined、字串、數值、布林等基本型別,typeof 足夠(記得 null 的例外)。
  • 在同一 frame 內判斷自定義型別的實例,instanceof 直觀好用。
  • 需要區分 Array、Date、RegExp,或必須應對跨 frame/跨 iframe 的物件,使用 Object.prototype.toString.call()。

最後一個實務提醒:在舊版 IE 中,某些宿主物件(例如 alert 這類由環境提供的功能)無法用上述方式判斷,遇到時需要單獨處理。

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