欧美亚洲中文,在线国自产视频,欧洲一区在线观看视频,亚洲综合中文字幕在线观看

      1. <dfn id="rfwes"></dfn>
          <object id="rfwes"></object>
        1. 站長資訊網(wǎng)
          最全最豐富的資訊網(wǎng)站

          如何獲取javascript變量的類型

          獲取javascript變量類型的方法:1、使用typeof操作符,語法“typeof 變量”;2、使用jQuery的“$.type()”方法;3、通過構(gòu)造函數(shù)來獲取類型。

          如何獲取javascript變量的類型

          本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5&&jquery1.10.0版、Dell G3電腦。

          在JavaScript中,如何準(zhǔn)確獲取變量的類型名是一個經(jīng)常使用的問題.

          但是常常不能獲取到變量的精確名稱,或者必須使用jQuery 中的方法,這里 我通過 typeof ,jQuery.type 和 通過構(gòu)造函數(shù)來獲取變量類型 這三種方法詳細(xì)介紹一遍.

          希望可以對你提供幫助.

          看到題目的第一眼,有些同學(xué)可能會想到 typeof 運(yùn)算符.


          使用 typeof 獲取基本的類型

          在JavaScript語言中,給出了使用 typeof 運(yùn)算符來獲取基本的類型名.(注意不是基本類型)

          這是 typeof 的全部用法

          01-typeof.htm

          console.log('typeof of 10 ~~~~' +typeof 10); console.log('typeof of "a" ~~~~' +typeof 'a'); console.log('typeof of true ~~~~' +typeof true); console.log('typeof of {} ~~~~' +typeof {}); console.log('typeof of /123/ ~~~~' +typeof /123/); console.log('typeof of function(){} ~~~~' +typeof function(){}); console.log('typeof of undefined ~~~~' +typeof undefined); console.log('typeof of null ~~~~' +typeof null);

          這是結(jié)果

          如何獲取javascript變量的類型

          按照上面的打印結(jié)果,總結(jié)出下面要注意的幾點

          • typeof (引用類型) 除了函數(shù), 都是 'object',比如 typeof /123/

          • typeof null 為'object'

          • typeof undefined 為 'undefined',通常, 如果使用兩等號, null == undefined 為真.

          • 轉(zhuǎn)換為數(shù)字的常見用法 "10"-0, 如果沒有轉(zhuǎn)換成功,返回NaN,由于NaN 的一個特性: NaN != NaN,故判斷轉(zhuǎn)換成功與否的常見做法: (這也是我參見 jQuery的源碼發(fā)現(xiàn)的,jQuery源碼讀100遍都不為過)
            ("10x" - 0) == ("10x" - 0); // 結(jié)果為假!
            如何獲取javascript變量的類型

          使用jQuery中的方法$.type()

          現(xiàn)在看看jQuery是怎么做的

          // 先申明一個對象,目的是用來做映射 var class2type = {}; // 申明一個core_toString() 的方法,得到最原始的toString() 方法,因為在很多對象中,toStrintg() 已經(jīng)被重寫  var core_toString() = class2type.toString;
          // 這里為 toStrintg() 后的結(jié)果和類型名做一個映射,申明一個core_toString() 后的結(jié)果,而值就是類型名 jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {     class2type[ "[object " + name + "]" ] = name.toLowerCase(); });

          因為 Object.prototype.toString() 方法調(diào)用結(jié)果如下

          var core_toString = {}.toString; console.log( core_toString.call(1) ); console.log( core_toString.call("11") ); console.log( core_toString.call(/123/) ); console.log( core_toString.call({}) ); console.log( core_toString.call(function(){}) ); console.log( core_toString.call([]) ); console.log( core_toString.call(true) ); console.log( core_toString.call(new Date()) ); console.log( core_toString.call(new Error() )); console.log( core_toString.call(null) ); console.log( core_toString.call(undefined) ); console.log( String(null) ); console.log( String(undefined) );

          如何獲取javascript變量的類型

          上面的打印結(jié)果與

          class2type[ "[object " + name + "]" ] = name.toLowerCase();

          不謀而合!

          這是jQuery.type 的核心方法

          type: function( obj ) {     if ( obj == null ) {         return String( obj );     }     // Support: Safari <= 5.1 (functionish RegExp)     return typeof obj === "object" || typeof obj === "function" ?         class2type[ core_toString.call(obj) ] || "object" :         typeof obj; },

          注意,為什么把 null 或者 undefined 單獨討論呢,因為 在一些版本瀏覽器中

          console.log(core_toString.call(null)); console.log(core_toString.call(undefined));

          這是會報錯的!

          如果是對象類型,另:由于 在一些低版本的瀏覽器中,typeof /123/ 會返回的是 "function" 而不是 "object",所以這里要判斷是否是函數(shù),要明白 這里的 typeof obj === function 不是為了函數(shù)討論的,因為函數(shù)本身就可以通過typeof 來得到類型.

          typeof obj === "object" || typeof obj === "function" ?         class2type[ core_toString.call(obj) ]

          就直接返回class2type 中鍵值對的結(jié)果,,如果不是,那么一定就是基本類型, 通過 typeof 就可以啦.

          class2type[ core_toString.call(obj) ] || "object" : // 這是防止一些未知情況的,如果未取到,就返回object

          但是 jQuery.type 有一個很大的缺陷

          這是一個自定義類型

          function Person(){    this.name = 'pawn'; } var p = Person.toString();

          // 注意,這里會打印 [object Object],通過上面的方法,無法得到精確的自定義類型
          這也是 它的一個大缺陷了!

          下面,我們通過構(gòu)造函數(shù)的方式來獲取精確類型

          通過構(gòu)造函數(shù)來獲取類型

          在理解這個方法之前,需要理解兩個點

          prorotype 原型屬性

          我們知道,任何對象或者函數(shù)都直接或者間接的繼承自O(shè)bject 或者 Function, (其實最終Function 是繼承自 Object 的,這屬于原型鏈的知識了)。那么,任何一個對象都具有原型對象 __proto__ (這個對象只在chrome 和 firefox 暴露,但是在其他瀏覽器中也是存在的),這個原型對象就是這個對象的構(gòu)造函數(shù)的原型屬性(這里可能有點繞).

          由于 任何函數(shù)都具有 原型屬性prototype,并且這個原型屬性具有一個默認(rèn)屬性 constructor,它是這個函數(shù)的引用,看下面的代碼

            function Person(){       this.name = 'pawn';   }   console.log(Person.prototype.constructor === Person);

          如何獲取javascript變量的類型

          發(fā)現(xiàn),這兩個東西其實一個東西

          但是,在某些情況下,需要這么寫

            function Person(){       this.name = 'pawn';   }   Person.protype = {       XX: ... ,       xx: ... ,       ...   }

          這么做,就會覆蓋原本的 protype 方法,那么construcor 就不存在了,這是,必須要顯示的申明這個對象

            Person.protype = {       construction: Person,       XX: ... ,       xx: ... ,       ...   }

          在jQuery的中,就是這么做的,

            jQuery.fn = jQuery.prototype = {     constructor: jQuery,     init: function( selector, context, rootjQuery ) {         var match, elem;

          關(guān)于 jQuery對象封裝的方式 也是非常值得研究


          • Function.prototype.toString()
            如何獲取javascript變量的類型

          注意,這里已經(jīng)不是熟悉 [object Object],而是 已經(jīng)重寫了.

          也就是,如果調(diào)用一個函數(shù)的toString() 方法.那么就會打印這個函數(shù)的函數(shù)體.

          如何獲取javascript變量的類型


          好了,經(jīng)過上面兩個步驟,你明白我要做什么了嗎?

          如何通過構(gòu)造函數(shù)來獲得變量的類型?

          判斷是否是基本類型

             var getType = function(obj){        if(obj == null){           return String(obj);        }        if(typeof obj === 'object' || typeof obj === 'fucntion'){            ...        }else{            // 如果不是引用類型,那么就是基本類型            return typeof obj        }    }

          如果是對象或者函數(shù)類型

             function Person(){        this.name = 'pawn';    }    var p = new Person();    console.log(p.constructor);

          如何獲取javascript變量的類型

          現(xiàn)在要做的事 : 如何將Person 提取出來呢?
          毋庸置疑,字符串切割那一套肯定可以辦到,但是太 low 啦!
          這里,我使用正則將Person提取出來

           var regex = /functions(.+?)(/    function Person(){     this.name = 'pawn';    }    var p = new Person();    var c = p.constructor    var regex = /functions(.+?)(/;    console.log('|' + regex.exec(c)[1] + '|');

          如何獲取javascript變量的類型

          使用name

          其實,除了上面的正則,每個函數(shù)還有一個name屬性,返回函數(shù)名,但是ie8 是不支持的.

          因此上面的代碼可以寫為:

          var getType = function(obj){     if(obj == null){         return String(obj);     }     if(typeof obj === 'object' || typeof obj === 'function'){          var constructor = obj.constructor;         if(constructor && constructor.name){             return constructor.name;         }         var regex = /functions(.+?)(/;         return regex.exec(c)[1];     }else{         // 如果不是引用類型,那么就是基本;類型         return typeof obj;     } };

          但是上面的代碼太丑啦,將其簡化

          簡化

          var getType = function(obj){     if(obj == null){         return String(obj);     }     if(typeof obj === 'object' || typeof obj === 'function'){          return obj.constructor && obj.constructor.name.toLowerCase() ||            /functions(.+?)(/.exec(obj.constructor)[1].toLowerCase();     }else{         // 如果不是引用類型,那么就是基本類型         return typeof obj;     } };

          還是比較麻煩,繼續(xù)簡化

          var getType = function(obj){     if(obj == null){        return String(obj);     }     return typeof obj === 'object' || typeof obj === 'function' ?       obj.constructor && obj.constructor.name && obj.constructor.name.toLowerCase() ||           /functions(.+?)(/.exec(obj.constructor)[1].toLowerCase():       typeof obj; };

          好了,已經(jīng)全部弄完了,寫個代碼測試一下:

          function Person(){     this.name = 'pawn'; } var p = new Person();  console.log(getType(p)); console.log(getType(1)); console.log(getType("a")); console.log(getType(false)); console.log(getType(/123/)); console.log(getType({})); console.log(getType(function(){})); console.log(getType(new Date())); console.log(getType(new Error())); console.log(getType( null)); console.log(getType( undefined));

          如何獲取javascript變量的類型

          【推薦學(xué)習(xí):javascript高級教程】

          贊(0)
          分享到: 更多 (0)
          網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號