详解js中typeof、instanceof与constructor
typeof返回一個表達(dá)式的數(shù)據(jù)類型的字符串,返回結(jié)果為js基本的數(shù)據(jù)類型,包括number,boolean,string,object,undefined,function.語法為typeof(data) 或 typeof data
instanceof則為判斷一個對象是否為某一數(shù)據(jù)類型,或一個變量是否為一個對象的實例;返回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));//true
19alert("h?instanceof?Object:"?+?(h?instanceof?Object));//true
20alert("o?instanceof?Object:"?+?(o?instanceof?Object));//true
21alert(typeof(h));//object
22//–>
23</script>
js中constructor較少使用,如果不是搜索到相關(guān)construtor相關(guān)的資料,我之前從沒有注意到j(luò)s還有這個函數(shù)。
使用typeof的一個不好的地方就是它會把Array還有用戶自定義函數(shù)都返回為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>
可以看到j(luò)s.constructor返回的是一些字符串,大家都應(yīng)該能看到這是一個function類型,此例為Number()為Number對象的構(gòu)造函數(shù),Number()用于將其參數(shù)轉(zhuǎn)換為數(shù)字number類型,并返回轉(zhuǎn)換結(jié)果(若不能轉(zhuǎn)換則返回 NaN)。
因此在以后的js判斷數(shù)據(jù)類型時可以使用以下方式來得到其詳細(xì)數(shù)據(jù)類型
1if((typeof o=="object") && (o.constructor==Number)){2…
3}
這里還要注意,constructor只能對已有變量進(jìn)行判斷,而typeof則可對未聲明變量進(jìn)行判斷(返回undefined)。
總結(jié)
以上是生活随笔為你收集整理的详解js中typeof、instanceof与constructor的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: coreldraw 复制填充渐变色
- 下一篇: JS数组”(array)和“对象”(ob