DIV CSS 佈局教程網

typeof 與 instanceof:兩種型別判斷方式的適用場合
編輯:JavaScript基礎知識     

typeof:取得型別名稱

typeof 用來取得一個變數的型別,可能的回傳值有限:number、boolean、string、function、object、undefined。

它的一個實用場景是判斷變數是否存在:

if (typeof a != "undefined") { /* ... */ }

請不要直接寫成 if (a),因為當 a 從未宣告時,直接取值會丟出錯誤。但要留意 typeof 的局限:對陣列、日期、null 等特殊物件,它一律回傳 "object",無法細分。

instanceof:判斷是否為某類的實例

當你想知道某個變數是不是陣列,或是不是某個建構函數所產生的實例,就該用 instanceof:

var a = new Array();
alert(a instanceof Array);   // true
alert(a instanceof Object);  // true,因為 Array 是 Object 的子類

function test() {}
var b = new test();
alert(b instanceof test);    // true

一個容易被誤解的地方:arguments

很多人以為函數裡的 arguments 是陣列。它「看起來」很像,但用 instanceof 一測就知道它並不是陣列物件。它只是類陣列(array-like),有 length 和索引,卻沒有陣列的那些方法。

語法與回傳規則

instanceof 會回傳一個布林值,用來指出物件是否為特定類別的實例:

result = object instanceof class

其中 object 是任意物件運算式,class 是任意已定義的物件類別。若 object 是 class 的實例則回傳 true;若不是,或 object 為 null,則回傳 false。

實作範例

function objTest(obj) {
    var i, t, s = "";
    t = new Array();
    t["Date"] = Date;
    t["Object"] = Object;
    t["Array"] = Array;
    for (i in t) {
        if (obj instanceof t[i]) {
            s += "obj is an instance of " + i + "\n";
        } else {
            s += "obj is not an instance of " + i + "\n";
        }
    }
    return s;
}

var obj = new Date();
alert(objTest(obj));

實務上的建議:判斷基本型別或「有沒有定義」用 typeof,判斷物件與類別的關係用 instanceof;若需要更精確的型別判定,也可以搭配 Object.prototype.toString.call()。

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