DIV CSS 佈局教程網

淺談 JavaScript 的資料型別檢測
編輯:關於JavaScript     

一、JavaScript 的資料

JavaScript 的資料分為兩種:簡單資料與複雜資料。簡單資料包含 number、string、boolean、undefined 和 null 五種;複雜資料只有一種,即 object。

二、資料型別檢測

1. 萬能的 typeof。先測試用 typeof 取得簡單資料型別:

// 取得變數 obj 的資料型別
function getType(obj) {
  return typeof (obj);
}
alert(getType(1));            // number
alert(getType("jeff wong"));  // string
alert(getType(true));         // boolean
alert(getType(undefined));    // undefined
alert(getType(null));         // object

正如你所看到的,透過 typeof,前四個簡單型別都在意料之中,但 typeof null 卻回傳 object。應該注意到,null 是 null 型別的唯一值,但 null 並不是 object,具有 null 值的變數也並非 object,所以單靠 typeof 並不能正確得到 null 型別。要正確取得簡單型別,只要稍作改進:

function getType(obj) {
  return (obj === null) ? "null" : typeof (obj);
}

接著試試複雜型別 object:

function Cat() {}
Cat.prototype.CatchMouse = function () {}
function getType(obj) {
  return (obj === null) ? "null" : typeof (obj);
}
var obj = new Object();      alert(getType(obj));   // object
var func = new Function();   alert(getType(func));  // function
var str = new String("x");   alert(getType(str));   // object
var num = new Number(10);    alert(getType(num));   // object
var time = new Date();       alert(getType(time));  // object
var arr = new Array();       alert(getType(arr));   // object
var reg = new RegExp();      alert(getType(reg));   // object
var garfield = new Cat();    alert(getType(garfield)); // object

我們看到,除了 Function 回傳 function 外,不論是常見內建物件 Object、String、Date,還是自訂的函數,透過 typeof 回傳的無一例外都是 object。但對於自訂函數,我們更希望得到它的「廬山真面目」(範例中即 Cat,而非 object),而 typeof 顯然不具備這種轉換能力。

2. constructor。既然萬能的 typeof 也有無解時,那麼如何判斷一個變數是否是自訂函數的實例?我們知道,JavaScript 的所有物件都有一個 constructor 屬性,這個屬性可以幫我們判斷 object 型別,對自訂函數同樣適用:

var obj = "jeff wong";
alert(obj.constructor == String); // true
obj = new Cat();
alert(obj.constructor == Cat);    // true

但下面的程式也值得測試:

var num = 1;
alert(num.constructor == Number); // true
var obj = null;
alert(obj.constructor);           // null 沒有 constructor 屬性
none = undefined;
alert(obj.constructor);           // undefined 沒有 constructor 屬性

實驗證明:數字型常量、null 和 undefined 都沒有 constructor 屬性。然而對於原型鏈繼承的情況,constructor 也不那麼好使了:

function Animal() {}
function Cat() {}
Cat.prototype = new Animal();
Cat.prototype.CatchMouse = function () {}
var obj = new Cat();
alert(obj.constructor == Cat);    // false ??
alert(obj.constructor == Animal); // true 可理解

原來對於原型鏈繼承,constructor 會指向父類。那怎麼辦?

3. 直觀的 instanceof。有請 instanceof 登場:

var garfield = new Cat();
alert(garfield instanceof Cat);    // true 毫無疑問
alert(garfield instanceof Animal); // true 可以理解

instanceof 沿著原型鏈向上查找,能正確判斷物件是否為某建構式的實例,是處理繼承情境下型別判斷的可靠方式。關於 JavaScript 的資料型別檢測,大致就總結到這裡。

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