JS中typeof与instanceof的区别

javaweiming 2011-06-16

JavaScript中typeof和instanceof常用来判断一个变量是否为空,或者是什么类型的。但它们之间还是有区别的:

typeof

typeof是一个一元运算,放在一个运算数之前,运算数可以是任意类型。

它返回值是一个字符串,该字符串说明运算数的类型。typeof一般只能返回如下几个结果:

number,boolean,string,function,object,undefined。我们可以使用typeof来获取一个变量是否存在,如if(typeofa!="undefined"){alert("ok")},而不要去使用if(a)因为如果a不存在(未声明)则会出错,对于Array,Null等特殊对象使用typeof一律返回object,这正是typeof的局限性。

网上的一个小例子:

<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<head>

<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>

<scriptlanguage="javascript"type="text/javascript">

document.write("typeof(1):"+typeof(1)+"<br>");

document.write("typeof(NaN):"+typeof(NaN)+"<br>");

document.write("typeof(Number.MIN_VALUE):"+typeof(Number.MIN_VALUE)+"<br>");

document.write("typeof(Infinity):"+typeof(Infinity)+"<br>");

document.write("typeof(\"123\"):"+typeof("123")+"<br>");

document.write("typeof(true):"+typeof(true)+"<br>");

document.write("typeof(window):"+typeof(window)+"<br>");

document.write("typeof(Array()):"+typeof(newArray())+"<br>");

document.write("typeof(function(){}):"+typeof(function(){})+"<br>");

document.write("typeof(document):"+typeof(document)+"<br>");

document.write("typeof(null):"+typeof(null)+"<br>");

document.write("typeof(eval):"+typeof(eval)+"<br>");

document.write("typeof(Date):"+typeof(Date)+"<br>");

document.write("typeof(sss):"+typeof(sss)+"<br>");

document.write("typeof(undefined):"+typeof(undefined)+"<br>")

</script>

<title>javascript类型测试</title>

</head>

<body>

</body>

</html>

instanceof

instance:实例,例子

ainstanceofb?alert("true"):alert("false");//a是b的实例?真:假

instanceof用于判断一个变量是否某个对象的实例,如vara=newArray();alert(ainstanceofArray);会返回true,同时alert(ainstanceofObject)也会返回true;这是因为Array是object的子类。再如:functiontest(){};vara=newtest();alert(ainstanceoftest)会返回

谈到instanceof我们要多插入一个问题,就是function的arguments,我们大家也许都认为arguments是一个Array,但如果使用instaceof去测试会发现arguments不是一个Array对象,尽管看起来很像。

另外:

测试vara=newArray();if(ainstanceofObject)alert('Y');elsealert('N');

得'Y’

但if(windowinstanceofObject)alert('Y');elsealert('N');

得'N'

所以,这里的instanceof测试的object是指js语法中的object,不是指dom模型对象。

使用typeof会有些区别

alert(typeof(window))会得object

转载自:http://blog.sina.com.cn/s/blog_532751d90100iv1r.html

相关推荐