首先我们看一个例子:
var a="string";
alert(a.length);
a.t=3;
alert(a.t);
大家可以想想答案是什么,显然第一个是6,那么第二个呢?有人可能想当然就说是3,但实际结果是undefined,为啥呢?因为把原始类型当作对象方式使用,例如访问length属性,或者增加属性。js都会智能转换成包装类型对象,相当于new了一个原始类型对象。当访问完成后,会把这个包装的对象销毁。因此这个答案的应该是"6 undefined"。
typeof
返回字符串,适合函数对象function和基本类型的检测,遇到null失效。
typeof 100;//“number”
typeof true;//“boolean”
typeof function;//“function”
typeof undefined;//“undefined”
typeof new Object();//"object"
typeof [1,2];//"object"
typeof NaN;//"number"
typeof null;//"object"
instanceof
- 判断对象类型,基于原型链判断,左操作数是对象,若不是返回false,右操作数为函数对象或函数构造器,若不是则抛出type error益处。
- 适合自定义对象,也可以用来检测原生对象。
- 注:不同window或iframe间的对象类型检测不能使用instanceof
[1,2] instanceof Array ===true;
new Object() instanceof Array ===false;
function Person(){}
function Student(){}
Student.prototype = new Person();
Student.prototype.constructor = Student;
var bosn = new Student();
bosn instanceof Student;//true
var one = new Person();
one instanceof Person;//true
one instanceof Student;//false
bosn instanceof Person;//true
Object.prototype.toString
适合内置对象和基元类型,遇到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]";