JS 類型檢測

PS:慕課心得(愛學習的妹紙,運氣不會太差?)html

首先咱們要先了解JS中的類型有哪些(每一個人看到的文檔不一樣,對類型的分類可能會有不一樣,如下是我的的理解)?數組

  1.原始類型:String Number Boolean Undefined Null函數

  2.引用類型:Function(特殊) Object Array ....(除原始類型外的都是引用類型)學習

如此多的類型,在使用的時候如何是檢測就成了一個很嚴肅的問題,因些下面對類型的檢測作了出歸類,希望對你有幫助:this

一.typeof( xxx)  || typeof  xxxspa

typeof   2            輸出   number.net

typeof   '222'                  輸出    stringprototype

typeof  true                    輸出     booleanhtm

typeof    undefined          輸出  undefined對象

typeof   (function(){})    輸出  function

typeof   null         輸出   object

typeof   {}           輸出   object

typeof    []           輸出   object

由上述示例不難看出,typeof 能檢測的類型仍是有限的,除 Null 之外的原始類型的檢測還算準確,而引用類型只能正確檢測出 Function ,因些引出 instanceof 來彌補 typeof 檢測時遺留的漏洞

2、xxx instanceof Object 

instance,故名思義,實例,例子,因此instanceof 用於判斷一個變量是不是某個對象的實例

var a=[];
console.log(a instanceof Array) //返回true 

另外,更重的一點是 instanceof 能夠在繼承關係中用來判斷一個實例是否屬於它的父類型。

例  function Foo(){}
  Foo.prototype = new Aoo();//JavaScript 原型繼承
  var foo = new Foo();
  console.log(foo instanceof Foo)//true
  console.log(foo instanceof Aoo)//true

上面的代碼中是判斷了一層繼承關係中的父類,在多層繼承關係中,instanceof 運算符一樣適用。

instanceof   參考:http://www.studyofnet.com/news/175.html

3、constructor

在W3C定義中的定義:constructor 屬性返回對建立此對象的數組函數的引用

就是返回對象相對應的構造函數。從定義上來講跟instanceof不太一致,但效果都是同樣的

如: (a instanceof Array)   //a是否Array的實例?true or false

   (a.constructor == Array)  // a實例所對應的構造函數是否爲Array? true or false

function employee(name,job,born){
    this.name=name;
    this.job=job;
    this.born=born;
}
var bill=new employee("Bill Gates","Engineer",1985);
console.log(bill.constructor); //function employee(name, jobtitle, born){this.name = name; this.jobtitle = job; this.born = born;}

4、Object.prototype.toString.call()

能夠說這個方法是最簡單的方法,之因此說它簡單,是由於這個檢測方法能檢測出任何類型,因此做爲一個很懶的程序猿,我選擇只記這個最簡單的方法,就是這麼任性(手動驕傲表情)

 咱們來試試這個玩兒意兒:

var   gettype=Object.prototype.toString

        gettype.call('aaaa')           輸出      [object String]

        gettype.call(2222)            輸出      [object Number]

        gettype.call(true)             輸出      [object Boolean]

        gettype.call(undefined)     輸出      [object Undefined]

        gettype.call(null)                  輸出   [object Null]

         gettype.call({})                   輸出   [object Object]

         gettype.call([])                    輸出   [object Array]
         gettype.call(function(){})     輸出   [object Function]

 對於這種方法,如下有幾個連接可供參考解釋:

http://blog.csdn.net/zhangw428/article/details/4171630

http://my.oschina.net/sfm/blog/33197

http://openxtiger.iteye.com/blog/1893378

相關文章
相關標籤/搜索