1、 typeof:用于检测基本的数据类型,对于引用类型的数据对象,则都是返回object
例如:
var s="my name is xiaojie";
var b=true;
var n=10;
var x;
function show(){ }
var o=new Object();
var m=null;
var arr=[1,2,3];
var json={'a':1,'b':2};
alert(typeof s) //string
alert(typeof b) //boolean
alert(typeof n) //number
alert(typeof x) //undefined
alert(typeof show) //function
alert(typeof o) //object
alert(typeof m) //object
alert(typeof arr) //object
alert(typeof json) //object
2、instanceof:用于检测引用类型的数据是什么类型的对象,如Array、Object、RegExp等 。使用格式如下
result=variable instanceof constructor
例如:
var arr=[1,2,3];
var json={'a':1,'b':2};
var reg=/\s+/g;
function show(){ }
alert(arr instanceof Array) //true
同时:alert(arr instanceof Object) //true
alert(json instanceof Object) //true
alert(reg instanceof RegExp) //true
同时:alert(reg instanceof Object) //true
alert(show instanceof Function) //true
同时:alert(show instanceof Object) //true
上述内容应该发现:所有引用类型的值都是Object的实例,因此在检测一个引用类型值和Object构造函数时,instanceof 操作符始终会返回true;,如果使用instanceof l来检测基本的数据类型的时候,都返回false.因为基本类型不是对象
3、constructor:该属性是任何对象本身具有的属性,而非继承来的属性。该属性返回对创建此对象的引用。
例如:var arr=new Array();
alert(arr.constructor == Array) //true;
alert(arr.constructor == Object) //false;
function Person()
{
this.name="xiaowang";
}
var person1=new Person();
var person2=new Person();
var test=new Object();
alert(person1.constructor == Person) //true;
alert(person2.constructor == Person) //true;
alert(person2.constructor == Object) //false;
alert(test.constructor == Object) //true;
对于constructor还需要多说一点是,对象的constructor都指向对象构造函数本身。例如
alert(person1.constructor)
结果为:
//function Person()
//{
// this.name="xiaowang";
//}
至此,typeof 、instanceof 、constructor的基本用法已经介绍完毕,更深入的用法后续更新