先准备几个变量
var a = "abcde.";
var b = 222;
var c= [1,2,3]; // 或者 new Array()
var d = new Date();
var e = function(){alert(111);};
var f = function(){this.name="rrrr";};
var g ={ 'name':'rrrr'}
1. 通用型 Object.prototype.toString.call(obj) , 注意大小写
console.log(Object.prototype.toString.call(a) === ‘[object String]’) //true;
console.log(Object.prototype.toString.call(b) === ‘[object Number]’) //true;
console.log(Object.prototype.toString.call(c) === ‘[object Array]’) //true;
console.log(Object.prototype.toString.call(d) === ‘[object Date]’) //true;
console.log(Object.prototype.toString.call(e) === ‘[object Function]’) //true;
console.log(Object.prototype.toString.call(f) === ‘[object Function]’) //true;
console.log(Object.prototype.toString.call(g) === ‘[object Object]’) //true;
2.typeof 方式 ,返回都是小写形式的数据类型名称字符串
console.log(typeof a) //string
console.log(typeof b) //number
console.log(typeof c) //object
console.log(typeof d) //object
console.log(typeof e) //function
console.log(typeof f) //function
console.log(typeof g) //object
判断:alert(typeof a == "string") ////true
3. instanceof , 判断已知对象类型,标准的js数据类型名称,注意大小写
console.log( a instanceof String) //true
console.log( d instanceof Date) // true
console.log( c instanceof Array) // true
console.log( g instanceof Object) //true
4. obj.constructor 对象的属性判断 用 === 符号,(与内置数据类型比较时为标准的js数据类型名称,注意大小写。也可与自定义数据类型比较,但是在继承时会有些问题)
function A(){};
function B(){};
A.prototype = new B(); //A继承自Bvar obj0 = new A();
console.log(obj0.constructor === A); // false
console.log(obj0.constructor === B); // true//这里用instanceof 则会都给出 true值
console.log(obj0 instanceof A) //true;
console.log(obj0 instanceof B) //true;
//解决construtor的问题通常是让对象的constructor手动指向自己:
obj0.constructor = A; //将自己的类赋值给对象的constructor属性
console.log(obj0.constructor === A) //true;
console.log(obj0.constructor === B) //false; //基类不会报true了;