JavaScript中常用的几种类型主要有:
- typeof
- instanceof
- Object.prototype.toString
- constructor
- duck type
typeof:适合基本类型及function检测,遇到null失效。
typeof 123 == number;
typeof undefined==undefined;
typeof null ==object;(失效)
objct.portotype.toString:通过{}.toString拿到,适合内置对象和基元类型,遇到null和undefined失效(IE678等返回[object Object]).
Object.prototype.toString.apply([]); === “[object Array]”;
Object.prototype.toString.apply(function(){}); === “[object Function]”;
Object.prototype.toString.apply(null); === “[object Null]”
Object.prototype.toString.apply(undefined); === “[object Undefined]”
instanceof:适合自定义对象,也可以用来检测原生对象,在不同iframe和window间检测时失效。
obj instanceof Object
注意:不同window或iframe间的对象类型检测不能使用instanceof!