typeof判断
typeof(2)---"number"
typeof(true)---"boolean"
typeof "str" ---"string"
typeof []---"object"
typeof function(){}---"function"
typeof {} ---"object"
typeof null---"object"
typeof undefined---"undefined"
使用typeof判断时,数组,对象,null都会判断为object,函数会被判断成为function
注:typeof的返回值都是字符串类型的,typeof(typeof(2))—“string”
instanceof判断
instanceof可以正确判断对象的类型,其内部运行机制是判断在其原型链中能否找到该类型的原型
2 instanceof Number --- false
true instanceof Boolean --- false
[] instanceof Array --- true
{} instanceof Object ---true
function(){} instanceof Function --- true
instanceof只能正确判断引用类型,而不能判断基本数据类型,instanceof运算符可以用来测试一个对象在其原型链中是否存在一个构造函数的prototype属性
constructor
(2).constructor === Number --- true
(true).constructor === Boolean --- true
("str").constructor === String --- true
([]).constructor === Array --- true
(function(){}).constructor === Function --- true
({}).constructor === Object --- true
constructor有两个作用,一个是判断数据的类型,另一个是对象实例通过constructor对象访问它的构造函数。
需要注意,如果创建一个对象来改变它的原型,constructor就不能用来判断数据类型了:
function Fn(){}
Fn.prototype = new Array();
var f = new Fn();
f.constructor === Fn --- false
f.constructor === Array --- true
Object.prototype.toString.call()
Object.prototype.toString.call()使用Object对象的原型方法toString来判断数据类型:
var a = Object.prototype.toString
a.call(2)---"[object Number]"
a.call(true)---"[object Boolean]"
a.call("str")---"[object String]"
a.call(function(){})---"[object Function]"
a.call({})---"[object Object]"
a.call(undefined)---"[object Undefined]"
a.call(null)---"[object Null]"
同样是检测对象obj调用toString方法,obj.toString()的结果和Object.prototype.toString.call(obj)的结果不一样,这是因为toString是Object的原型方法,而Array,Function等类型作为Object的实例,都重写了toString方法。不同的对象类型调用toString方法时,根据原型链的知识,调用的是对应的重写之后的toString方法(返回对象的具体类型),所以采用obj.toString()不能得到其对象类型,只能将obj转换成字符串类型,因此,在想要得到对象类型的具体类型时,应该调用Object原型上的toString方法