且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript中typeof和instanceof的区别

更新时间:2022-08-21 10:59:30

 

typeof

 

typeof 是一个一元运算,放在一个运算数之前,运算数可以是任意类型。它返回值是一个字符串,该字符串说明运算数的类型。

typeof一般只能返回如下几个结果:number,boolean,string,function,object,undefined。

可以使用typeof来获取一个变量是否存在,如if(typeof a != "undefined") 。而不要去使用if(a)因为如果a不存在(未声明)则会出错。

对于Array,Null等特殊对象使用typeof一律返回object,这正是typeof的局限性。

 

小测试

typeof(1): number

typeof(NaN): number

typeof(Number.MIN_VALUE): number

typeof(Infinity): number

typeof("123"): string

typeof(true): boolean

typeof(window): object

typeof(Array()): object

typeof(function(){}): function

typeof(document): object

typeof(null): object

typeof(eval): function

typeof(Date): function

typeof(sss): undefined

typeof(undefined): undefined

 

注意点:

如果检测对象是函数,那么操作符返回"function" ,如果检测对象是正则表达式的时候

在Safari和Chrome中使用typeof的时候会错误的返回"function"

其他的浏览器返回的是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)。

 

注意点

 

注意点一: 

就是function的arguments,也许都认为arguments是一个Array,但使用instaceof去测试会发现arguments不是一个Array对象。

 

注意点二: 

if (window instanceof Object) alert("Y");else alert("N");得N。

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

typeof会有些区别lert(typeof(window))会得object。

 

 

原帖地址:http://www.linuxs.org/?p=1015