typeof一般用来获取一个变量或者表达式的类型。
> typeof undefined
'undefined'
> typeof null // well-known bug
'object'
> typeof true
'boolean'
> typeof 123
'number'
> typeof "abc"
'string'
> typeof function() {}
'function'
> typeof {}
'object'
> typeof []
'object'
> typeof unknownVariable
'undefined'
function SuperType(){
}
console.log(typeof(SuperType)); //function
可以看到typeof一般返回值有undefined、Object(包括数组,NULL, 对象)、String、number、Boolean、function.
我们可以使用typeof来获取一个变量是否存在,如
if(typeof a!=”undefined”){},
而不要去使用if(a)因为如果a不存在(未声明)则会出错,
正因为typeof遇到null,数组,对象时都会返回object类型,所以当我们要判断一个对象是否是数组时
或者判断某个变量是否是某个对象的实例则要选择使用另一个关键语法instanceof.
instanceofxao操作符是一个双目运算符。判断一个对象是否是另一个对象的实例。
function SuperType(){
}
var instance = new Supertype();
alert(instance instanceof SuperType); //true;
alert(instance instanceof Object); //true ; 所有引用类型默认都是Object的实例
alert(instance instanceof Function); //false;
//instance是一个对象,而不是函数
alert(SuperType instanceof Function); //true ;
var a=new Array();alert(a instanceof Array); //true;