姓名:雷瀟 16030110083????
轉(zhuǎn)載自:http://blog.51cto.com/mazey/2048538
【嵌牛導(dǎo)讀】JavaScript中typeof,instanceof,hasOwnProperty,in用法區(qū)別
【嵌牛鼻子】typeof,instanceof,hasOwnProperty,in
【嵌牛提問】typeof,instanceof,hasOwnProperty,in的用法區(qū)別都掌握了嗎
【嵌牛正文】一. typeof操作符
typeof操作符用于返回正在使用值的類型。
// 使用原始值letmNull =null;letmUndefined =undefined;letmString ='mazey';letmNumber =123;letmBoolean =true;letmFunction =function(){returntrue;};// 用構(gòu)造函數(shù)的方式new一個(gè)實(shí)例letoString =newString('cherrie');letoRegExp =newRegExp('^[0-9]+$');letoFunction =newFunction('x','y','return x + y');letoObj = {};letoNew =newObject();// typeof值console.log(typeofmNull);// objectconsole.log(typeofmUndefined);// undefinedconsole.log(typeofmString);// stringconsole.log(typeofmNumber);// numberconsole.log(typeofmBoolean);// booleanconsole.log(typeofmFunction);// functionconsole.log(typeofoString);// objectconsole.log(typeofoRegExp);// objectconsole.log(typeofoFunction);// functionconsole.log(typeofoObj);// objectconsole.log(typeofoNew);// object
在《JavaScript啟示錄》中new RegExp()介紹會(huì)返回function,但是事實(shí)上我在chrome控制臺(tái)中看到的是object。
于是我console.log(new RegExp('^[0-9]+$')),打印出來的是字符串/^[0-9]+$/。
console.log(newRegExp('^[0-9]+$'));// /^[0-9]+$/console.log(RegExp);// ? RegExp() { [native code] } 原始值console.log(String);// ? String() { [native code] } 原始值console.log(/^[0-9]+$/);// /^[0-9]+$/console.log(newRegExp('^[0-9]+$') ===/^[0-9]+$/);// falseconsole.log(RegExp('^[0-9]+$') ===/^[0-9]+$/);// false
綜上可以看出現(xiàn)版本RegExp和String Number一樣屬于JavaScript的原始值。
Math作為JavaScript中的靜態(tài)對(duì)象回返回什么呢?
console.log(typeofMath);// objectconsole.log(typeofMath.PI);// numberconsole.log(typeofMath.ceil);// function
所以Math的__proto__還是Object,typeof還能返回對(duì)象的屬性和方法的類型。
typeof使用場(chǎng)景
1.判斷某個(gè)變量是否已定義
console.log(typeofaaa);// 'undefined'// 判斷if(typeofbbb ==='undefined') {console.log('變量未定義');}
2.區(qū)分原始值和復(fù)雜值(對(duì)象值)
因?yàn)閺?fù)雜值往往返回object,當(dāng)然有個(gè)例外就是原始值里面的null也返回object,然后function作為Object的實(shí)例也是復(fù)雜值。
// 判斷是否時(shí)復(fù)雜值(對(duì)象值)functionisObject(m){return(typeofm ==='function'|| (typeofm ==='object'&& m !==null));}console.log(isObject(newRegExp('123')));// trueconsole.log(isObject('123'));// falseconsole.log(isObject(String('123')));// falseconsole.log(isObject(null));// false// 判斷是否是原始值functionisNative(m){return(m ===null|| (typeofm !=='object'&&typeofm !=='function'));}console.log(isNative(newRegExp('123')));// falseconsole.log(isNative('123'));// trueconsole.log(isNative(String('123')));// trueconsole.log(isNative(null));// true
3.檢測(cè)某個(gè)變量是否是函數(shù)
當(dāng)使用閉包時(shí)判斷是函數(shù)后再進(jìn)行下一步。
functionqqq(){leta =0;letb =function(){? ? ? ? a++;console.log(a);? ? };returnb;}letccc = qqq();console.log(typeofccc);// functionif(typeofccc ==='function') {? ? ccc();// 1ccc();// 2ccc();// 3ccc();// 4}
二. instanceof操作符
通過使用instanceof操作符,可以確定一個(gè)對(duì)象是否是特定構(gòu)造函數(shù)的實(shí)例,返回true或false。
instanceof只適用于構(gòu)造函數(shù)創(chuàng)建返回的復(fù)雜對(duì)象和實(shí)例。
任何時(shí)間判斷一個(gè)對(duì)象(復(fù)雜值)是否是Object的實(shí)例時(shí),它都將返回true,因?yàn)樗袑?duì)象都繼承自O(shè)bject()構(gòu)造函數(shù)。
letoFather =function(){this.firstName ='mazey';};oFather.prototype.lastName ='qian';// 實(shí)例letoSon =newoFather();console.log(oSoninstanceofoFather);// true// 繼承l(wèi)etnFather =function(){};nFather.prototype =newoFather();nFather.construction = nFather;console.log(nFather.firstName);// undefinedconsole.log(nFather.prototype.lastName);// qianconsole.log(nFatherinstanceofoFather);// falseconsole.log(newnFather()instanceofnFather);// true// 相對(duì)于Object來說console.log('123'instanceofObject);// falseconsole.log(newString('123')instanceofObject);// true 構(gòu)造出來的實(shí)例console.log(nullinstanceofObject);// false
instanceof使用場(chǎng)景
判斷在一個(gè)繼承關(guān)系中實(shí)例是否屬于它的父類。
// 繼承l(wèi)etoFather =function(){};letnFather =function(){};nFather.prototype =newoFather();nFather.construction = nFather;letnSon =newnFather();console.log(nSoninstanceofnFather);// trueconsole.log(nSoninstanceofoFather);// true
三. in操作符和hasOwnProperty方法
in操作符可以檢查一個(gè)對(duì)象的屬性,包括來自原型鏈的屬性,hasOwnProperty()方法可以檢查來自非原型鏈屬性的對(duì)象。
例如現(xiàn)在有一個(gè)對(duì)象let obj = {name: 'mazey'};,name是它自身定義的屬性,toString是它從原型鏈上繼承下來的屬性。
letobj = {name:'mazey'};console.log('name'inobj);// trueconsole.log('toString'inobj);// trueconsole.log('name'inObject);// trueconsole.log(obj.hasOwnProperty('name'));// trueconsole.log(obj.hasOwnProperty('toString'));// falseconsole.log(Object.hasOwnProperty('name'));// true
所以in操作符查找的范圍更廣一點(diǎn),可以用hasOwnProperty()判斷是否是對(duì)象自身的屬性,而不是通過類似obj.prototype.foo = 'foo';這樣定義的。
hasOwnProperty方法使用場(chǎng)景
在實(shí)際項(xiàng)目中經(jīng)常使用for...in...來遍歷對(duì)象中可枚舉的屬性,但是for...in...常常把原型obj.prototype.xxx中的屬性也列舉出來,所以在循環(huán)的時(shí)候可以加上hasOwnProperty()方法判斷下。
functionobj0(){this.name ='mazey',this.age ='24'};obj0.prototype.gender ='male';letobj1 =newobj0();// 打印所有可枚舉屬性for(letkeyinobj1) {console.log(key);// name age gender 從原型鏈上繼承下來的屬性也會(huì)被打印出來}// 過濾掉原型鏈上的屬性for(letkeyinobj1) {if(obj1.hasOwnProperty(key)) {console.log(key);// name age}}
四. 總結(jié)
1.typeof可以判斷使用值的類型,注意null返回object。
2.instanceof驗(yàn)證構(gòu)造函數(shù)構(gòu)造出來的實(shí)例,可以用來判斷一個(gè)對(duì)象是否屬于一個(gè)父類。
3.hasOwnProperty方法常常與in操作符搭配使用,用來遍歷一個(gè)對(duì)象自身的屬性。
五. 相關(guān)擴(kuò)展
1.刪除對(duì)象的屬性
若想把一個(gè)對(duì)象的自身屬性完全刪除,要使用delete操作符。
letobj0 = {name:'mazey',age:24};// 刪除age屬性deleteobj0.age;console.log(obj0.hasOwnProperty('age'));// falseconsole.log('age'inobj0);// false// 試著刪除原型鏈上的屬性 toStringdeleteobj0.toStringconsole.log('toString'inobj0);// true
需要注意的是delete不會(huì)刪除原型鏈上的屬性。
2.可枚舉
每個(gè)對(duì)象的屬性都分為可枚舉和不可枚舉屬性,可以使用propertyIsEnumerable()方法來檢查哪些屬性是可枚舉的。
每個(gè)對(duì)象都有一個(gè)propertyIsEnumerable方法。此方法可以確定對(duì)象中指定的屬性是否可以被for...in(for...in語句以任意順序遍歷一個(gè)對(duì)象的可枚舉屬性。對(duì)于每個(gè)不同的屬性,語句都會(huì)被執(zhí)行)循環(huán)枚舉,但是通過原型鏈繼承的屬性除外。如果對(duì)象沒有指定的屬性,則此方法返回false。
有的資料說只要能被for..in遍歷的屬性就是可枚舉的,實(shí)際上要排除從原型鏈上繼承下來的屬性,只有自身的屬性是可枚舉的。
// 第一個(gè)構(gòu)造函數(shù)functionConFun0(){this.firstName ='mazey';}ConFun0.prototype.firstCom ='bang';// 第二個(gè)構(gòu)造函數(shù)functionConFun1(){this.secondName ='qian';}// 繼承第一個(gè)ConFun1.prototype =newConFun0();ConFun1.prototype.constructor = ConFun1;// 實(shí)例letobj =newConFun1();obj.girlName ='cherrie';// 是否可枚舉console.log(obj.propertyIsEnumerable('constructor'));// falseconsole.log(obj.propertyIsEnumerable('firstName'));// falseconsole.log(obj.propertyIsEnumerable('firstCom'));// false// 通過原型鏈繼承的屬性不是可枚舉console.log(obj.propertyIsEnumerable('secondName'));// trueconsole.log(obj.propertyIsEnumerable('girlName'));// truefor(letkeyinobj) {console.log(key);// secondName girlName (原型鏈上的屬性也會(huì)被打印出來->) firstName constructor firstCom}console.log(`---分割線---`);for(letkeyinobj) {// 過濾掉原型鏈上的屬性if(obj.hasOwnProperty(key)) {console.log(key);// secondName girlName}}
所以可枚舉的屬性一定能被for..in循環(huán)遍歷出來,但是for...in循環(huán)遍歷出來的屬性不一定是可枚舉的,需排除從原型鏈上繼承下來的屬性,這里可以通過hasOwnProperty()方法過濾掉不可枚舉屬性。