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()方法來(lái)忽略繼承屬性。
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方法來(lái)獲取正確的結(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. JavaScript設(shè)計(jì)模式之策略模式實(shí)現(xiàn)原理詳解2. idea設(shè)置代碼格式化的方法步驟3. Python tkinter制作單機(jī)五子棋游戲4. 八種Vue組件間通訊方式合集(推薦)5. GIT相關(guān)-IDEA/ECLIPSE工具配置的教程詳解6. Django Auth用戶認(rèn)證組件實(shí)現(xiàn)代碼7. 完美實(shí)現(xiàn)CSS垂直居中的11種方法8. vue項(xiàng)目登錄成功拿到令牌跳轉(zhuǎn)失敗401無(wú)登錄信息的解決9. JSP頁(yè)面跳轉(zhuǎn)方法大全10. ASP中if語(yǔ)句、select 、while循環(huán)的使用方法
