DIV CSS 佈局教程網

JavaScript 判斷物件類型的三種方法與跨 frame 難題
編輯:JavaScript基礎知識     

JavaScript 裡能拿來偵測物件類型的工具主要有三個:typeof、instanceof,以及物件的 constructor 屬性。三者能力各異,也各有盲點。

1)typeof 運算符

typeof 是一元運算符,回傳一個描述運算元類型的字串,例如 "number"、"string"、"boolean"、"object"、"function"、"undefined"(也可用來判斷變數是否存在)。

但它能力有限,對 Date、RegExp 一律回 "object":

typeof {};           // "object"
typeof [];           // "object"
typeof new Date();   // "object"

所以它只在區分「物件」與「原始型別」時有用。要分辨一種物件與另一種物件,必須換用其他手段。

2)instanceof 運算符

instanceof 要求左邊是物件,右邊是類別名稱或建構函式。若左邊物件是右邊類別的實例則回 true;若不是,或物件為 null,則回 false。

[] instanceof Array;      // true
[] instanceof Object;     // true
[] instanceof RegExp;     // false
new Date instanceof Date; // true

因此判斷陣列可以這樣寫:

function isArray(arr) {
  return arr instanceof Array;
}

3)constructor 屬性

每個物件都有 constructor 屬性,指向初始化它的建構函式。常見策略是先用 typeof 確認是物件,再看 constructor:

function isArray(arr) {
  return typeof arr == "object" && arr.constructor == Array;
}

跨 frame 時兩招都會失效

instanceof 與 constructor 在多數情況下夠用,很多 JavaScript 框架就是用這兩招判斷陣列。但在跨 frame 場景下它們會失敗,原因是不同 frame(iframe)中建立的陣列不共享同一份 prototype。

<script>
window.onload = function () {
  var iframe_arr = new window.frames[0].Array;
  alert(iframe_arr instanceof Array);      // false
  alert(iframe_arr.constructor == Array);  // false
}
</script>

正解:跨原型鏈呼叫 Object.prototype.toString

Object.prototype.toString(o) 執行時會做三件事:取得物件 o 的 [[Class]] 內部屬性、把它與 "[object " 和 "]" 串接、回傳結果。

Object.prototype.toString.call([]);      // "[object Array]"
Object.prototype.toString.call(/reg/ig); // "[object RegExp]"

於是就有了健壯的陣列判斷:

function isArray(arr) {
  return Object.prototype.toString.call(arr) === "[object Array]";
}

這個方法獲得國外多位 JavaScript 大師認可,即將發布的 jQuery 1.3 也採用它來偵測陣列。prototype.js 的一位維護者寫了這個函式,用來取出物件的內部型別名:

/**
 * Returns internal [[Class]] property of an object
 *
 * Ecma-262, 15.2.4.2
 * Object.prototype.toString( )
 *
 * __getClass(5);       // => "Number"
 * __getClass({});      // => "Object"
 * __getClass(/foo/);   // => "RegExp"
 * __getClass('');      // => "String"
 * __getClass(true);    // => "Boolean"
 * __getClass([]);      // => "Array"
 * __getClass(undefined);// => "Window"
 * __getClass(Element); // => "Constructor"
 */
function __getClass(object) {
  return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
};

進一步:做一套通用型別偵測

var is = {
  types: ["Array", "Boolean", "Date", "Number", "Object", "RegExp", "String", "Window", "HTMLDocument"]
};
for (var i = 0, c; c = is.types[i++];) {
  is[c] = (function (type) {
    return function (obj) {
      return Object.prototype.toString.call(obj) == "[object " + type + "]";
    }
  })(c);
}

alert(is.Array([]));        // true
alert(is.Date(new Date())); // true
alert(is.RegExp(/reg/ig));  // true
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved