JS中的instanceof和typeof
来源:互联网 发布:九本满防防御数据 编辑:程序博客网 时间:2024/05/29 08:32
对于instanceof和typeof,以前看到过,但是只对typeof用到的相对更多一些,最近看js的设计模式,很多用到了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,因为其具有数组一样的访问性质及方式,可以由arguments[n]来访问对应的单个参数的值,并拥有数组长度属性length。但如果使用instaceof去测试会发现arguments不是一个Array对象,尽管看起来很像。
下面是我的一个非常简单的测试页面,大家可以调试一下,在加深印象的同时也可以看结论是不是正确的:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>instanceof</title>
</head>
<body>
<hr /><br />
<p style="color:#F00">
如果我们希望获取一个对象是否是数组,或判断某个变量是否是某个对象的实例则要选择使用instanceof。<br />
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。<br />
谈到instanceof我们要多插入一个问题,就是function的arguments,我们大家也许都认为arguments是一个Array,但如果使用instaceof去测试会发现arguments不是一个Array对象,尽管看起来很像。<br />
</p>
<hr />
<script type="text/javascript">
function a(){
this.a="a";
this.b="b";
alert(typeof(arguments)); //Object
alert(arguments instanceof Object); //true
alert(arguments instanceof Array); //false
}
var test=new a();
alert(test instanceof a); //true
alert(typeof(test)); //Object
</script>
</body>
</html>
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- JS中的instanceof和typeof
- js中的instanceof 和 typeof
- js 中的 typeof 和 instanceof 的区别
- typeof和instanceof在js中的应用
- JS typeof和instanceof用法
- JavaScript中的typeof和instanceof
- JavaScript 中的typeof 和 instanceof
- sliverlight-Resources-2
- TCP NAT 穿透原理相关文档
- NYOJ-453 小珂的烦恼【模拟||找规律】
- 业务规则引擎-jboss Drools Expert
- ORA-06552错误的解决
- JS中的instanceof和typeof
- Ext核心API详解-Ext.tree.TreePanel
- 对项目质量的无止境追求---读《微软的秘密》有感
- Sharepoint2010-常用方法技巧总结
- [Silverlight学习记录]Resources-1
- Ext.form.ComboBox最常用的一些属性和方法
- 异常来自 HRESULT:0x80040E14
- objective C中的@class, SEL , IMP等灵活机制(五)
- 委托的使用实例