A JavaScript Fancier

伟大的javascript技术研究中...

  IT博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  304 随笔 :: 0 文章 :: 479 评论 :: 0 Trackbacks


   对于instanceof和typeof,以前偶尔的用到过,特别是typeof用到的相对更多一些,今日研究ext源码,很多地方都用到了instanceof,突然觉得他们两个有些相似但也应该有他们区别,网上看了一些文章,对它们之间的关系有了一定的了解。

instanceof和typeof都能用来判断一个变量是否为空或是什么类型的变量。
typeof用以获取一个变量的类型,typeof一般只能返回如下几个结果:number,boolean,string,function,object,undefined。我们可以使用typeof来获取一个变量是否存在,如if(typeof a!="undefined"){},而不要去使用if(a)因为如果a不存在(未声明)则会出错,对于Array,Null等特殊对象使用typeof一律返回object,这正是typeof的局限性。

如果我们希望获取一个对象是否是数组,或判断某个变量是否是某个对象的实例则要选择使用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。

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

posted on 2007-10-10 15:15 Yemoo'S JS Blog 阅读(19080) 评论(7)  编辑 收藏 引用 所属分类: javascript技巧总结

评论

# re: JS中的instanceof和typeof 2008-03-18 14:01 LSCD
Thanks!  回复  更多评论
  

# re: JS中的instanceof和typeof 2008-07-04 22:13 J.W
测试
javascript:{var a=new Array();if (a instanceof Object) alert('Y');else alert('N');}
得'Y’


javascript:{if (window instanceof Object) alert('Y');else alert('N');}
我测试得'N'?

(又 javascript:alert(typeof(window)) 得 object)  回复  更多评论
  

# re: JS中的instanceof和typeof 2008-12-16 08:40 徐尧
楼上的,这里的object是指js语法中的object,不是指dom模型对象。  回复  更多评论
  

# re: JS中的instanceof和typeof 2008-12-27 11:27 n.h
@徐尧
那么 需要判断dom中object 怎么做呢?
用nodeName?  回复  更多评论
  

# re: JS中的instanceof和typeof 2012-07-07 18:39 chauvet
楼主,有个地方说的不对,
a instanceof Object 得到true并不是因为 Array是Object的子对象,而是因为 Array的prototype属性构造于Object,Array的父级是Function。  回复  更多评论
  

# re: JS中的instanceof和typeof 2012-09-27 00:44 zernmal
本文相当不错,谢啦   回复  更多评论
  

# re: JS中的instanceof和typeof 2014-02-09 23:38 wersion
@J.W
我在Ie以及在ff上都测试是为Y的。不知道你是哪里出错了  回复  更多评论
  

只有注册用户登录后才能发表评论。