js屬性對(duì)象的hasOwnProperty方法的使用
Object的hasOwnProperty()方法返回一個(gè)布爾值,判斷對(duì)象是否包含特定的自身(非繼承)屬性。
判斷自身屬性是否存在var o = new Object();o.prop = ’exists’;function changeO() { o.newprop = o.prop; delete o.prop;}o.hasOwnProperty(’prop’); // truechangeO();o.hasOwnProperty(’prop’); // false判斷自身屬性與繼承屬性
function foo() { this.name = ’foo’ this.sayHi = function () { console.log(’Say Hi’) }}foo.prototype.sayGoodBy = function () { console.log(’Say Good By’)}let myPro = new foo()console.log(myPro.name) // fooconsole.log(myPro.hasOwnProperty(’name’)) // trueconsole.log(myPro.hasOwnProperty(’toString’)) // falseconsole.log(myPro.hasOwnProperty(’hasOwnProperty’)) // fasleconsole.log(myPro.hasOwnProperty(’sayHi’)) // trueconsole.log(myPro.hasOwnProperty(’sayGoodBy’)) // falseconsole.log(’sayGoodBy’ in myPro) // true遍歷一個(gè)對(duì)象的所有自身屬性
在看開源項(xiàng)目的過程中,經(jīng)常會(huì)看到類似如下的源碼。for...in循環(huán)對(duì)象的所有枚舉屬性,然后再使用hasOwnProperty()方法來忽略繼承屬性。
var buz = { fog: ’stack’};for (var name in buz) { if (buz.hasOwnProperty(name)) { alert('this is fog (' + name + ') for sure. Value: ' + buz[name]); } else { alert(name); // toString or something else }}注意 hasOwnProperty 作為屬性名
JavaScript 并沒有保護(hù) hasOwnProperty 屬性名,因此,可能存在于一個(gè)包含此屬性名的對(duì)象,有必要使用一個(gè)可擴(kuò)展的hasOwnProperty方法來獲取正確的結(jié)果:
var foo = { hasOwnProperty: function() { return false; }, bar: ’Here be dragons’};foo.hasOwnProperty(’bar’); // 始終返回 false// 如果擔(dān)心這種情況,可以直接使用原型鏈上真正的 hasOwnProperty 方法// 使用另一個(gè)對(duì)象的`hasOwnProperty` 并且call({}).hasOwnProperty.call(foo, ’bar’); // true// 也可以使用 Object 原型上的 hasOwnProperty 屬性O(shè)bject.prototype.hasOwnProperty.call(foo, ’bar’); // true
參考鏈接
到此這篇關(guān)于js屬性對(duì)象的hasOwnProperty方法的使用的文章就介紹到這了,更多相關(guān)js hasOwnProperty內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 詳解Java內(nèi)部類——匿名內(nèi)部類2. 淺談SpringMVC jsp前臺(tái)獲取參數(shù)的方式 EL表達(dá)式3. python pymysql鏈接數(shù)據(jù)庫(kù)查詢結(jié)果轉(zhuǎn)為Dataframe實(shí)例4. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)5. idea設(shè)置自動(dòng)導(dǎo)入依賴的方法步驟6. 使用Python和百度語(yǔ)音識(shí)別生成視頻字幕的實(shí)現(xiàn)7. 教你如何寫出可維護(hù)的JS代碼8. IDEA版最新MyBatis程序配置教程詳解9. xml中的空格之完全解說10. css代碼優(yōu)化的12個(gè)技巧
