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(鸭子类型)
通过检测特征来检测类型
举个栗子,如果我们要证明这是一只鸭子,我们可以通过检测它的叫声(嘎嘎叫),走路的形态(一摇一摆),如果满足其独有特征,则可以证明这是一只鸭子
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(鸭子类型)
通过检测特征来检测类型
举个栗子,如果我们要证明这是一只鸭子,我们可以通过检测它的叫声(嘎嘎叫),走路的形态(一摇一摆),如果满足其独有特征,则可以证明这是一只鸭子
相关文章推荐
- [BZOJ1030][JSOI2007]文本生成器(AC自动机+dp)
- 基于JSP在线答题程序设计
- javascript面向对象之闭包
- js配合锚点实现动画滚动与监听
- JavaScript之数据类型
- JavaScript反选-全选-全不选代码
- Newtonsoft.Json 自定义序列化特性
- JavaScript进阶基础一
- [练习4]js学习之图片的水平滚动
- js 事件捕获与事件冒泡例子
- JSON
- [练习3]js学习之图片的竖直滚动
- ES6-let带来了更简单的块级作用域
- JavaScript基础
- JS总结
- [练习2]js学习之文本数值滚动
- js设计模式-命令模式
- js事件
- JSON in google Maps
- Chapter 15:JSON Assignment