typeof、instanceof和constructor
阿新 • • 發佈:2018-05-09
UC 創建 console job 檢測 object 存在 type style
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 = newNumber(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; }
typeof、instanceof和constructor