DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> WEB網站前端 >> 前端技巧
JavaScript 型別判斷的四種方法與各自的坑
編輯:前端技巧     

型別判斷是 JavaScript 裡看似簡單、細節卻很多的課題。常用的手段有四種:typeof、instanceof、constructor 與 prototype,各有適用範圍與陷阱。

先準備幾個待測變數:

var a = "iamstring.";
var b = 222;
var c = [1,2,3];
var d = new Date();
var e = function () { alert(111); };
var f = function () { this.name = "22"; };

1、typeof

typeof a  // "string"
typeof b  // "number"
typeof c  // "object"
typeof d  // "object"
typeof e  // "function"
typeof f  // "function"

最常見的做法。注意它回傳的是字串,所以比較時右邊要打引號:

typeof a == "string"   // true
typeof a == String     // false

typeof 的強項是判斷 function 與基本型別,弱點是遇到陣列、日期、自訂物件時一律回 "object",無從分辨。(另外 typeof null 回 "object",這是語言本身的歷史遺留。)

2、instanceof

c instanceof Array      // true
d instanceof Date       // true
f instanceof Function   // true
f instanceof function   // false

它沿原型鏈向上檢查,因此能應付繼承情境。注意右側必須是建構函式且大小寫不能錯,寫成 function(小寫關鍵字)會直接報錯。

3、constructor

c.constructor == Array      // true
d.constructor == Date       // true
e.constructor == Function   // true

constructor 的問題出在繼承。當原型鏈被改寫,constructor 會指向錯誤的類:

function A() {}
function B() {}
A.prototype = new B();   // A 繼承自 B
var aObj = new A();
aObj.constructor === B   // true,但其實應該是 A
aObj.constructor === A   // false

instanceof 不會有這個困擾,無論直接或間接繼承都會回 true:

aObj instanceof B   // true
aObj instanceof A   // true

修法是在改寫原型之後手動把 constructor 指回自己:

A.prototype = new B();
A.prototype.constructor = A;
aObj.constructor === A   // true
aObj.constructor === B   // false

4、Object.prototype.toString

Object.prototype.toString.call(a) === '[object String]'    // true
Object.prototype.toString.call(b) === '[object Number]'    // true
Object.prototype.toString.call(c) === '[object Array]'     // true
Object.prototype.toString.call(d) === '[object Date]'      // true
Object.prototype.toString.call(e) === '[object Function]'  // true

寫法繁瑣、字串大小寫也不能出錯,但它是最通用、最可靠的方式,連 cross-realm 的物件(例如 iframe 裡建立的陣列)都能正確辨識。

怎麼選

日常判斷基本型別用 typeof 就夠了;已知大方向是某類物件時,用 instanceof 最簡潔;需要萬無一失的通用判斷,就用 Object.prototype.toString.call()。

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