JavaScript-数据类型-类型检测

介绍四种能力检测的方法:

typeof

instanceeof

Object.prototype.toString.apply( )

constructor

duck type



typeof  适合基本类型function检测,遇到null失效


instanceof  适合自定义对象原生对象检测

左边必须是对象,右边必须是函数对象函数构造器 

原理:检测左边对象的原型链上是否包含右边对象的prototype属性

注意:因为是按引用判断对象 ,所以不同的window或iframe间检测类型不能使用instanceof

 

Object.prototype.toString.apply( obj )  ===  “[object Obj]” 

适合内置对象基元类型,遇到null和undefined失效

Object.prototype.toString.apply( [ ] )  ===  “[object Array]”

Object.prototype.toString.apply( function(){}) === “[object Function]”

Object.prototype.toString.apply( null )  ===  “[object Null]”              //IE6/7/8中返回“[object Object]”

Object.prototype.toString.apply( undefined)=== “[object Undefined]”  // IE6/7/8中返回“[objectObject]”

 

constructor  返回对创建此对象的数组函数的引用

object.constructor  ==  Obj

例:

<scripttype="text/javascript">

var test=new Array();

if (test.constructor==Array)

{

document.write("This is anArray");

}

if (test.constructor==Boolean)

{

document.write("This is aBoolean");

}

if (test.constructor==Date)

{

document.write("This is a Date");

}

if (test.constructor==String)

{

document.write("This is aString");

}

</script>

 

Duck type(鸭子类型)   

通过检测特征来检测类型

举个栗子,如果我们要证明这是一只鸭子,我们可以通过检测它的叫声(嘎嘎叫),走路的形态(一摇一摆),如果满足其独有特征,则可以证明这是一只鸭子

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值