类型检测分为五种:
1.typeof
2.(对象)obj instanceof Object(函数对象、函数构造器)//左边的操作数的对象的原型链上是否有右操作函数构造器的prototype属性
例子:
[1,2] instanceof Array===true;
new Object() instanceof Array===false;
3.Object.prototype.toString
例子:
var arr=[1,2];
//通过call指定arr数组为Object.prototype对象中的toString方法的上下文
Object.prototype.toString.call(arr); //"[object Array]"
4.constructor //constructor 属性返回对创建此对象的数组函数的引用。
例子1:
<script type="text/javascript">
var test=new Array();
if (test.constructor==Array)
{
document.write("This is an Array");
}
if (test.constructor==Boolean)
{
document.write("This is a Boolean");
}
if (test.constructor==Date)
{
document.write("This is a Date");
}
if (test.constructor==String)
{
document.write("This is a String");
}
</script>
输出:
This is an Array
例子2:
function employee(name,job,born)
{
this.name=name;
this.job=job;
this.born=born;
}
var bill=new employee("Bill Gates","Engineer",1985);
document.write(bill.constructor);
输出:
function employee(name, job, born)
{this.name = name; this.job = job; this.born = born;}
5.duck type
总结:
typeof
适合基本类型及function 检测,遇到null失效
[[Class]] Object.prototype.toString
通过{}.toString拿到适合内置对象和基元类型,遇到null和undefined失效(IE678等返回[object Object])
instanceof
适合自定义对象,也可以用来检测原生对象,在不同iframe和window间检测时失效