typeof、instanceof和constructor
1.js中判断是否是对象经常用到这三个关键字或者属性。下面一一介绍:
(1)typeof运算符,通常会返回:"undefined"、"object"、"boolean"、"number" 和 "string"的字符串。数组和对象都返回"object"。数组和对象的typeof返回一致为"object"。
var o = {age: 20}; typeof o //"object" var a = [1,2,3]; typeof a //"object" var n = 20; typeof n //"number" var b; typeof b //"undefined" var f = false; typeof b //"boolean" var s = 'str'; typeof s //"string"
(2)instanceof运算符用来判断一个构造函数的prototype属性所指向的对象是否存在另外一个要检测对象的原型链上。可以区分数组和对象。
var a = {s:2}; a instanceof Object //true var a = [2]; a instanceof Object //true var a = [2]; a instanceof Array //true var a = 1; a instanceof Number //false var a = new Number(1); a instanceof Number //true var a = '3'; a instanceof String //false var a = new String('3'); a instanceof String //true function Person(){}; var p =new Person(); console.log(p instanceof Person); //true
(3)constructor返回对创建此对象的数组函数的引用。可以区分数组和对象。
//用法一: var a = {name:2}; a.constructor === Object //true var a = [1,2]; a.constructor === Object //false var a = 1; a.constructor === Number //true var a = 'test'; a.constructor === String //true var a = new Date();a.constructor === Date //true //用法二: function employee(name,job,born) { this.name=name; this.job=job; this.born=born; } var bill=new employee("Bill Gates","Engineer",1985); document.write(bill.constructor); function employee(name,job,born) { this.name=name; this.job=job; this.born=born; }