js中typeof、instanceof
2017-03-02 本文已影响0人
jasmine_jing
typeof用以获取一个变量或者表达式的类型,typeof一般只能返回如下几个结果:
number,boolean,string,function(函数),object(NULL,数组,对象),undefined。
alert(typeof (123));//typeof(123)返回"number"
alert(typeof ("123"));//typeof("123")返回"string"
我们可以使用typeof来获取一个变量是否存在,如if(typeof a!="undefined"){},而不要去使用if(a)因为如果a不存在(未声明)则会出错,
instanceof则为判断一个对象是否为某一数据类型,或一个变量是否为一个对象的实例;返回boolean类型
语法为 o instanceof A
正因为typeof遇到null,数组,对象时都会返回object类型,所以当我们要判断一个对象是否是数组时,或者判断某个变量是否是某个对象的实例则要选择使用另一个关键语法instanceof
instanceof用于判断一个变量是否某个对象的实例,如
var a=new Array();
alert(a instanceof Array);
//true
同时alert(a instanceof Object)也会返回true;这是因为Array是object的子类。
再如:
function test(){};
var a=new test();
alert(a instanceof test)
//true
<script type="text/javascript">
<!–
alert("typeof(1):" + typeof(1));//number
alert("typeof(\"abc\"):" + typeof("abc"));//string
alert("typeof(true):" +typeof(true));//boolean
alert("typeof(2009-2-4):" + typeof(2009-2-4));//number
alert("typeof(\"2009-2-4\"):" + typeof("2009-2-4"));//string
alert("typeof(m):" + typeof(m));//undefined
var d=new Date();
alert("typeof(d):" + typeof(d));//object
function Person(){};
alert("typeof(Person):" + typeof(Person));//function
var a=new Array();
alert("typeof(a):" + typeof(a));//object
alert("a instanceof Array:" + (a instanceof Array));
var h=new Person();
var o={};
alert("h instanceof Person:" + (h instanceof Person));//true
alert("h instanceof Object:" + (h instanceof Object));//true
alert("o instanceof Object:" + (o instanceof Object));//true
alert(typeof(h));//object
//–>
</script>