JavaScript 類型檢測(cè)

JavaScript 類型檢測(cè)

本文介紹JavaScript的幾種類型檢測(cè)的方法,以及其各自的適用范圍。

JavaScript 的數(shù)據(jù)類型

JavaScript中的數(shù)據(jù)類型有null、undefined、布爾值、字符串、數(shù)字、對(duì)象,這6種數(shù)據(jù)類型,其中前五種是基本數(shù)據(jù)類型,對(duì)象是復(fù)雜數(shù)據(jù)類型。

JavaScript中檢測(cè)類型有如下幾種方法:

  1. typeof
  2. instanceof
  3. constructor
  4. duck type (鴨子類型)

typeof

typeof返回字符串,適用于函數(shù)對(duì)象基本類型的檢測(cè)(注:遇null失效),各種類型的返回值如下:

代碼 結(jié)果
typeof 1 "number"
typeof true "boolean"
typeof function "function"
typeof [3,4,5] "object"
typeof new Object() "object"
typeof NaN "number"
typeof undefined "undefined"
typeof null "object"(null被認(rèn)為是一個(gè)空的對(duì)象引用)

不適用的范圍:

  1. typeof null返回"object",所以不適合判斷null

如需判斷某個(gè)對(duì)象是否是null,可以使用obj === null

instanceof

instanceof 是一個(gè)二元操作符,左邊是要判斷的對(duì)象,右面是函數(shù)對(duì)象或者構(gòu)造器

instanceof 是基于原型鏈進(jìn)行判斷,判斷左邊的原型鏈上是否有右邊的類型(和Java的intanceof類型)

function Dog() {}  
  
  
// Dog繼承于Animal  
Dog.prototype = new Animal();  
Dog.prototype.constructor = Dog;  
  
  
var dog = new Dog();  
console.log(dog instanceof Dog); // true dog直接用Dog初始化,所以為真  
  
  
var cat = new Animal();  
console.log(cat instanceof Animal); // true cat直接用Animal初始化,所以為真  
  
  
console.log(cat instanceof Dog); //false   
console.log(dog instanceof Animal); //true  

在判斷dog是否是Animal類型時(shí),dog對(duì)象有一個(gè)原型_proto_,該原型會(huì)指向其構(gòu)造器 Dog 的_proto_,但是Animal不等于Dog,所以該原型鏈會(huì)繼續(xù)向上查找,Dog的_proto_指向了Animal,所以最終dog instanceof Animal 返回true

不適用的范圍:在多窗口和多框架的子頁(yè)面的web應(yīng)用中兼容性不好。

原因:在兩個(gè)不同框架頁(yè)面創(chuàng)建的兩個(gè)相同的對(duì)象繼承與兩個(gè)相同但互相獨(dú)立的原型對(duì)象(例如:創(chuàng)建兩個(gè)數(shù)組),其中一個(gè)框架頁(yè)面中的數(shù)組不是另一個(gè)框架頁(yè)面中的Array()構(gòu)造函數(shù)的實(shí)例,instanceof 運(yùn)算結(jié)果返回false。

constructor

不適用范圍:

  1. 不適合判斷null和undefined,因?yàn)闆](méi)有contructor屬性
  2. contructor可能被改寫
  3. 和instanceof類型,在多窗口和多框架下無(wú)法工作
  4. 并非所有的對(duì)象都包含contructor 屬性

contructor的使用如下:

代碼 結(jié)果
var x=1; x.constructor Number
var x=true; x.constructor Boolean
var x = function(){};x.constructor Function
var x='string';x.constructor String

注意:nullundefined沒(méi)有constructor

duck type

不要關(guān)注對(duì)象的類是什么,而是關(guān)注對(duì)象能做什么。

例如,我們?cè)谂袛嘁粋€(gè)對(duì)象是否是Array的實(shí)例的時(shí)候,可以通過(guò)判斷對(duì)象是否含有一個(gè)非負(fù)的length屬性來(lái)判斷,這是一個(gè)必要非充分條件。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容