介绍四种能力检测的方法:
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(鸭子类型)
通过检测特征来检测类型
举个栗子,如果我们要证明这是一只鸭子,我们可以通过检测它的叫声(嘎嘎叫),走路的形态(一摇一摆),如果满足其独有特征,则可以证明这是一只鸭子