DIV CSS 佈局教程網

搞懂 JavaScript 的 typeof 與 instanceof:為什麼它們總是不夠用
編輯:JavaScript基礎知識     

寫 JavaScript 時,typeof 與 instanceof 幾乎是必用的兩個運算子,但許多人都有過同樣的挫折感:用了它們,卻常常拿不到自己想要的答案。社群裡甚至流傳一種說法——這兩個運算子可能是 JavaScript 最大的設計遺憾,因為很難從它們身上得到精確的結果。

typeof:回傳一個字串型別名稱

typeof 會回傳代表運算式型別的字串,結果落在 JavaScript 的基本型別裡:number、boolean、string、object、undefined、function。看定義似乎沒問題:

var a = 1;
console.log(typeof a);        // "number"

var b = new Number(1);
console.log(typeof b);        // "object"

麻煩就在這裡。既然呼叫了 typeof,理應得到精確的型別;不管變數是用字面值建立,還是用建構函式建立,b 明明包裝的是數字,卻只回報「object」。用字面值與用建構函式寫出來的東西,在 typeof 眼中是兩種生物,這正是它讓人惱火的地方。

用 Object.prototype.toString 取出真正的型別

精確的型別資訊其實藏在每個值的內部屬性 [[Class]] 裡,而讀取它最可靠的方式是借用定義在 Object.prototype 上的 toString 方法:

var a = 1;
var b = new Number(1);
console.log(Object.prototype.toString.call(a));  // [object Number]
console.log(Object.prototype.toString.call(b));  // [object Number]

兩個值都被正確辨識為 Number。只要把固定前後綴切掉,就能得到乾淨的結果:

console.log(Object.prototype.toString.call(a).slice(8, -1));  // Number
console.log(Object.prototype.toString.call(b).slice(8, -1));  // Number

封裝成一個通用的型別判斷函式

function is(obj, type) {
  var clas = Object.prototype.toString.call(obj).slice(8, -1);
  return obj !== undefined && obj !== null && clas === type;
}

先看 typeof 的原始表現,問題一目了然:

var a1 = 1,               a2 = Number(1);
var b1 = "hello",         b2 = new String("hello");
var c1 = [1, 2, 3],       c2 = new Array(1, 2, 3);

typeof a1;  // number
typeof a2;  // object
typeof b1;  // string
typeof b2;  // object
typeof c1;  // object
typeof c2;  // object

改用剛剛寫好的 is(),六個值全部判斷正確:

is(a1, "Number");  // true
is(a2, "Number");  // true
is(b1, "String");  // true
is(b2, "String");  // true
is(c1, "Array");   // true
is(c2, "Array");   // true

不過也別把 typeof 一棍子打死。它真正的用武之地其實很樸素:判斷一個變數是否已經宣告、是否已經被賦值。這個用途上,它依然是首選。

instanceof:看的是原型鏈

instanceof 的定義是判斷一個物件是否為某個型別的實例,也就是某變數是不是某建構函式所產生的物件。但拿它來比對內建模組型別時,同樣會讓人失望:

"abc" instanceof String;                    // false
"abc" instanceof Object;                    // false
new String("abc") instanceof String;        // true
new String("abc") instanceof Object;        // true

原因不難理解:instanceof 沿著物件串的原型鏈往上找,而字面值並不是物件,自然找不到。只有在比較自訂的建構函式時,它才會忠實反映繼承關係:

function Person() {}
function Man() {}
Man.prototype = new Person();

new Man() instanceof Man;      // true
new Man() instanceof Person;   // true

結論很實際:需要精確的型別名稱時,用 Object.prototype.toString;需要判斷繼承關係時,用 instanceof;只想確認變數有沒有被定義,typeof 依然綽綽有餘。選對工具,比抱怨工具好用得多。

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