hasOwnProperty
生活随笔
收集整理的這篇文章主要介紹了
hasOwnProperty
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
hasOwnProperty() 方法會返回一個布爾值,這個方法可以用來檢測一個對象是否含有特定的自身(非繼承)屬性。
1、for...in循環(huán)時為什么要在里面加上if(obj.hasOwnProperty(name))的判斷
這段代碼的意思是:判斷一個對象里是否含有某個非繼承屬性。
for...in 循環(huán)會遍歷所有可枚舉屬性,加上hasOwnProperty()方法,可以忽略掉繼承屬性,這樣就能確保遍歷的是Obj的可枚舉的自身屬性。
適用于:含有繼承屬性的對象,也就是除了Object的所有對象
看下面的例子:
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) // foo console.log(myPro.hasOwnProperty('name')) // true console.log(myPro.hasOwnProperty('toString')) // false console.log(myPro.hasOwnProperty('hasOwnProperty')) // fasle console.log(myPro.hasOwnProperty('sayHi')) // true console.log(myPro.hasOwnProperty('sayGoodBy')) // false console.log('sayGoodBy' in myPro) // true2、為什么有的地方用Object.prototype.hasOwnProperty.call(obj,name)
Javascript 并沒有保護 hasOwnProperty 為關鍵字或保留字。因此,會有這樣一種情況:對象自己改寫了hasOwnProperty方法,比如下面代碼中該方法永遠返回false。如果另一個不知情的人使用了foo,并想通過foo.hasOwnProperty判斷foo是否含有某個屬性時就會永遠返回false,這顯然是有問題的。
這時候可以借助于Object.prototype.hasOwnProperty或{}.hasOwnProperty來判斷對象是否含有某個非繼承屬性。
適用于:不確定Object類型變量是否改寫了hasOwnProperty的情況
var foo = { hasOwnProperty: function() { return false; }, bar: 'Here be dragons' }; foo.hasOwnProperty('bar'); // 總是返回 false // 使用另一個 hasOwnProperty 并將 this 設置為 foo 來調用它 {}.hasOwnProperty.call(foo, 'bar'); // true3、總結
- 建議增加 hasOwnProperty 進行判斷,可以有效避免擴展本地原型而引起的錯誤
- 如果對一個Object類型的內部屬性不是很確定,可以通過{}.hasOwnProperty.call(obj,name)或Object.prototype.hasOwnProperty.call(obj,name)的方式判斷
總結
以上是生活随笔為你收集整理的hasOwnProperty的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第二十一章:变换(三)
- 下一篇: 腾讯云10亿扶持小程序:3元套餐可能免费