詳解js中typeof、instanceof與constructor

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   使用   sp   

詳解js中typeof、instanceof與constructor

typeof返回一個運算式的資料類型的字串,返回結果為js基本的資料類型,包括number,boolean,string,object,undefined,function.文法為typeof(data) 或 typeof data

instanceof則為判斷一個對象是否為某一資料類型,或一個變數是否為一個對象的執行個體;返回boolean類型
文法為 o instanceof A

以下為綜合執行個體:


 1<script type="text/javascript">
 2<!–
 3alert("typeof(1):" + typeof(1));//number
 4alert("typeof(\"abc\"):" + typeof("abc"));//string
 5alert("typeof(true):" +typeof(true));//boolean
 6alert("typeof(2009-2-4):" + typeof(2009-2-4));//number
 7alert("typeof(\"2009-2-4\"):" + typeof("2009-2-4"));//string
 8alert("typeof(m):" + typeof(m));//undefined
 9var d=new Date();
10alert("typeof(d):" + typeof(d));//object
11function Person(){};
12alert("typeof(Person):" + typeof(Person));//function
13var a=new Array();
14alert("typeof(a):" + typeof(a));//object
15alert("a instanceof Array:" + (a instanceof Array));
16var h=new Person();17var o={};18alert("h instanceof Person:" + (h instanceof Person));//true19alert("h instanceof Object:" + (h instanceof Object));//true20alert("o instanceof Object:" + (o instanceof Object));//true21alert(typeof(h));//object22//–>23</script>

查看效果

js中constructor較少使用,如果不是搜尋到相關construtor相關的資料,我之前從沒有注意到js還有這個函數。

使用typeof的一個不好的地方就是它會把Array還有使用者自訂函數都返回為object

1<script type="text/javascript">
2<!–
3var j=2;
4alert(typeof(j));//number
5alert("j.constructor:" + j.constructor);//function …
6alert(typeof(j.constructor));//function
7//–>
8</script>

 

查看示範

可以看到js.constructor返回的是一些字串,大家都應該能看到這是一個function類型,此例為Number()為Number對象的建構函式,Number()用於將其參數轉換為數字number類型,並返迴轉換結果(若不能轉換則返回 NaN)。

因此在以後的js判斷資料類型時可以使用以下方式來得到其詳細資料類型

1if((typeof o=="object") && (o.constructor==Number)){
2…
3}

這裡還要注意,constructor只能對已有變數進行判斷,而typeof則可對未聲明變數進行判斷(返回undefined)。

原文來自:http://www.51obj.cn/

詳解js中typeof、instanceof與constructor

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.