2019獨角獸企業重金招聘Python工程師標準>>>
概述
hasOwnProperty()
?方法用來判斷某個對象是否含有指定的自身屬性。
語法
obj.hasOwnProperty(prop)
參數
prop
要檢測的屬性名稱。
描述
所有繼承了?Object.prototype
?的對象都會從原型鏈上繼承到?hasOwnProperty
?方法,這個方法可以用來檢測一個對象是否含有特定的自身屬性,和?in
?運算符不同,該方法會忽略掉那些從原型鏈上繼承到的屬性。
示例
例1:使用?hasOwnProperty
?方法判斷某對象是否含有特定的自身屬性
下面的例子檢測了對象?o
?是否含有自身屬性?prop:
o?=?new?Object();o.prop?=?'exists';function?changeO()?{o.newprop?=?o.prop;delete?o.prop;}o.hasOwnProperty('prop');???//?返回?truechangeO();o.hasOwnProperty('prop');??//?返回?false
例2:自身屬性和繼承屬性的區別
下面的例子演示了?hasOwnProperty
?方法對待自身屬性和繼承屬性的區別:
o?=?new?Object();o.prop?=?'exists';o.hasOwnProperty('prop');????????????//?返回?trueo.hasOwnProperty('toString');?????????//?返回?falseo.hasOwnProperty('hasOwnProperty');???//?返回?false
例3:遍歷一個對象的所有自身屬性
下面的例子演示了如何在遍歷一個對象的所有屬性時忽略掉繼承屬性,注意這里?for..in
?循環只會遍歷可枚舉屬性,這通常就是我們想要的,直接使用?Object.getOwnPropertyNames()
?方法也可以實現類似的需求。
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????}}
例4:?hasOwnProperty
?方法有可能被遮蔽
如果一個對象擁有自己的?hasOwnProperty
?方法, 則原型鏈上的同名方法會被遮蔽(shadowed):
var?foo?=?{hasOwnProperty:?function()?{return?false;},bar:?'Here?be?dragons'};foo.hasOwnProperty('bar');?//?始終返回?false//?如果擔心這種情況,可以直接使用原型鏈上真正的?hasOwnProperty?方法({}).hasOwnProperty.call(foo,?'bar');?//?trueObject.prototype.hasOwnProperty.call(foo,?'bar');?//?true