of + 检测目标 或者 typeof (检测目标),该方法适用于基本数据类型和函数的检测(遇到null失效),返回的结果都是字符串
typeof 100 ? “number”
typeof true ? “boolean”
typeof("hello")? "String"
typeof Function ? “Function”
typeof undefined? “undefined”
typeof null? “Object”? 历史遗留的问题,为了兼容
typeof NaN? “number” ? 判断NaN的方法可以用isNaN(NaN)来判断,如果返回true就是NaN
typeof new Object() ? “Object”
typeof [1,2] ? "Object"
大家可能注意到了,typeof在检测对象类型的时候是无法区分的,此时我们就要用第二种方法instanceof
2.instanceof运算符(适用于自定义对象或者原生对象数据类型的检测),基于原型链的类型检测
比如判断一个对象是不是数组: [1,2] instanceof Array 返回 true
obj instanceof Object ? :它期望左操作数obj 是一个对象,如果是一个数字1,2,3或者true,false时就会直接返回false。
它期望右操作数是一个函数对象或者是函数构造器,如果不是就会抛出Typeerror异常
instanceof 工作的一个大概的原理就是它会判断左操作数这样一个对象的原型链上是否有右边这个构造函数的prototype属性
我们举一个例子:
function Person(){}
function Student(){}
Student.prototype = new Person();
Student.protype.constructor = Student
var a = new Person();
var b = new Student();
-----------------------------------------
a instanceof Person ? // true
b instanceof Student ? //true
a instanceof Student ? //false
b instanceof Person ? //true
注意:不同window之间和跨iframe之间是不可以使用instanceof的,虽然看着是同一个对象但是在不同window之间和跨iframe之间是不同的对象,每个iframe下都有自己???一套原型链,跨frame实例化的对象彼此是不共享原型链,因此会返回false
3.Object.prototype.toString 函数方法
Object.prototype.toString.call()或者Object.prototype.toString.apply()
例如:
Object.prototype.toString.call([]) ? ? //"[object Array]"
Object.prototype.toString.call(function(){}) //"[object Function]"
Object.prototype.toString.call(undefined) //"[object Undefined]"
Object.prototype.toString.call(null)? ? ? //"[object Null]"
?
注意:1.解决了跨iframe 失效的问题
2.IE 6,7,8下? Object.prototype.toString.call(null或undefined)? ? ? //"[object Object]"
4.constructor方法
function?A(){};?
function?B(){};?
A.prototype?=?new?B();?
var?aObj?=?new?A();?
--------------------------------
aObj.constructor?===?B;?
aObj.constructor?===?A;?
? ? ? 注意:类继承时会出现问题
5.duck type(鸭子类型)
比如检测数组时,我们可以检测他有没有push()方法等等