您的位置:首页 > Web前端 > JavaScript

JavaScript-数据类型-类型检测

2016-04-04 23:11 465 查看
介绍四种能力检测的方法:

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 an
4000
Array");

}

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(鸭子类型)   

通过检测特征来检测类型

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

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: