JavaScript中typeof,instanceof,hasOwnProperty,in用法區(qū)別

姓名:雷瀟 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一個實(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()介紹會返回function,但是事實(shí)上我在chrome控制臺中看到的是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)對象回返回什么呢?

console.log(typeofMath);// objectconsole.log(typeofMath.PI);// numberconsole.log(typeofMath.ceil);// function

所以Math的__proto__還是Object,typeof還能返回對象的屬性和方法的類型。

typeof使用場景

1.判斷某個變量是否已定義

console.log(typeofaaa);// 'undefined'// 判斷if(typeofbbb ==='undefined') {console.log('變量未定義');}

2.區(qū)分原始值和復(fù)雜值(對象值)

因?yàn)閺?fù)雜值往往返回object,當(dāng)然有個例外就是原始值里面的null也返回object,然后function作為Object的實(shí)例也是復(fù)雜值。

// 判斷是否時(shí)復(fù)雜值(對象值)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.檢測某個變量是否是函數(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òu)造函數(shù)實(shí)例,返回true或false。

instanceof只適用于構(gòu)造函數(shù)創(chuàng)建返回的復(fù)雜對象實(shí)例

任何時(shí)間判斷一個對象(復(fù)雜值)是否是Object的實(shí)例時(shí),它都將返回true,因?yàn)樗袑ο蠖祭^承自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// 相對于Object來說console.log('123'instanceofObject);// falseconsole.log(newString('123')instanceofObject);// true 構(gòu)造出來的實(shí)例console.log(nullinstanceofObject);// false

instanceof使用場景

判斷在一個繼承關(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操作符可以檢查一個對象的屬性,包括來自原型鏈的屬性,hasOwnProperty()方法可以檢查來自非原型鏈屬性的對象。

例如現(xiàn)在有一個對象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()判斷是否是對象自身的屬性,而不是通過類似obj.prototype.foo = 'foo';這樣定義的。

hasOwnProperty方法使用場景

在實(shí)際項(xiàng)目中經(jīng)常使用for...in...來遍歷對象中可枚舉的屬性,但是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 從原型鏈上繼承下來的屬性也會被打印出來}// 過濾掉原型鏈上的屬性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í)例,可以用來判斷一個對象是否屬于一個父類。

3.hasOwnProperty方法常常與in操作符搭配使用,用來遍歷一個對象自身的屬性。

五. 相關(guān)擴(kuò)展

1.刪除對象的屬性

若想把一個對象的自身屬性完全刪除,要使用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不會刪除原型鏈上的屬性。

2.可枚舉

每個對象的屬性都分為可枚舉和不可枚舉屬性,可以使用propertyIsEnumerable()方法來檢查哪些屬性是可枚舉的。

每個對象都有一個propertyIsEnumerable方法。此方法可以確定對象中指定的屬性是否可以被for...in(for...in語句以任意順序遍歷一個對象的可枚舉屬性。對于每個不同的屬性,語句都會被執(zhí)行)循環(huán)枚舉,但是通過原型鏈繼承的屬性除外。如果對象沒有指定的屬性,則此方法返回false。

有的資料說只要能被for..in遍歷的屬性就是可枚舉的,實(shí)際上要排除從原型鏈上繼承下來的屬性,只有自身的屬性是可枚舉的。

// 第一個構(gòu)造函數(shù)functionConFun0(){this.firstName ='mazey';}ConFun0.prototype.firstCom ='bang';// 第二個構(gòu)造函數(shù)functionConFun1(){this.secondName ='qian';}// 繼承第一個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 (原型鏈上的屬性也會被打印出來->) 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()方法過濾掉不可枚舉屬性。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容