javascript
JavaScript 中 obj.hasOwnProperty(prop) 方法
語法
obj.hasOwnProperty(prop)參數
prop
要檢測的屬性的?String?字符串形式表示的名稱,或者?Symbol。
返回值
用來判斷某個對象是否含有指定的屬性的布爾值?Boolean。
描述
所有繼承了?Object?的對象都會繼承到?hasOwnProperty?方法。這個方法可以用來檢測一個對象是否含有特定的自身屬性;和?in?運算符不同,該方法會忽略掉那些從原型鏈上繼承到的屬性。
備注
即使屬性的值是?null?或?undefined,只要屬性存在,hasOwnProperty?依舊會返回?true。
o = new Object(); o.propOne = null; o.hasOwnProperty('propOne'); // 返回 true o.propTwo = undefined; o.hasOwnProperty('propTwo'); // 返回 true示例
使用?hasOwnProperty?方法判斷屬性是否存在
下面的例子檢測了對象?o?是否含有自身屬性?prop:
o = new Object(); o.hasOwnProperty('prop'); // 返回 false o.prop = 'exists'; o.hasOwnProperty('prop'); // 返回 true delete o.prop; o.hasOwnProperty('prop'); // 返回 false自身屬性與繼承屬性
下面的例子演示了?hasOwnProperty?方法對待自身屬性和繼承屬性的區別:
o = new Object(); o.prop = 'exists'; o.hasOwnProperty('prop'); // 返回 true o.hasOwnProperty('toString'); // 返回 false o.hasOwnProperty('hasOwnProperty'); // 返回 false遍歷一個對象的所有自身屬性
下面的例子演示了如何在遍歷一個對象的所有屬性時忽略掉繼承屬性,注意這里?for...in? 循環只會遍歷可枚舉屬性,所以不應該基于這個循環中沒有不可枚舉的屬性而得出?hasOwnProperty?是嚴格限制于可枚舉項目的(如同?Object.getOwnPropertyNames())。
var buz = {fog: 'stack' };for (var name in buz) {if (buz.hasOwnProperty(name)) {console.log('this is fog (' +name + ') for sure. Value: ' + buz[name]);}else {console.log(name); // toString or something else} }使用?hasOwnProperty?作為屬性名
JavaScript 并沒有保護?hasOwnProperty?這個屬性名,因此,當某個對象可能自有一個占用該屬性名的屬性時,就需要使用外部的?hasOwnProperty?獲得正確的結果:
var foo = {hasOwnProperty: function() {return false;},bar: 'Here be dragons' };foo.hasOwnProperty('bar'); // 始終返回 false// 如果擔心這種情況, // 可以直接使用原型鏈上真正的 hasOwnProperty 方法 ({}).hasOwnProperty.call(foo, 'bar'); // true// 也可以使用 Object 原型上的 hasOwnProperty 屬性 Object.prototype.hasOwnProperty.call(foo, 'bar'); // true注意,只有在最后一種情況下,才不會新建任何對象。
直接上代碼來個示例:
function ObjWithProto(){this.foo = 'foo_val' } ObjWithProto.prototype.bar = 'bar_val' var dict = new ObjWithProto() dict.foobar = 'foobar_val'dict.hasOwnProperty('foo') // true dict.hasOwnProperty('foobar') // true dict.hasOwnProperty('bar') // false再來看 for…in , 遍歷一個對象的可枚舉屬性
for(let i in dict){console.log(i) } //foo // foobar // bar //原型鏈上的bar也獲取到了為了遍歷一個對象的所有屬性時忽略掉繼承屬性,使用hasOwnProperty()來過濾該對象上的繼承屬性。
for(let i in dict){if(dict.hasOwnProperty(i)){console.log(i)} } //foo //foobar再來看看原型連上的一個繼承
function ObjWithProto(){this.foo = 'foo_val'}ObjWithProto.prototype.bar = 'bar_val'function Person(){this.name = 'Person_name'}Person.prototype = new ObjWithProto()var _child = new Person()for(let i in _child){console.log(i)}console.log('------ this is a line -------')for(let i in _child){if(_child.hasOwnProperty(i)){console.log(i)}}_child.hasOwnProperty('name') // true_child.hasOwnProperty('foo') // false_child.hasOwnProperty('bar') // false//name//foo//bar//------ this is a line -------//name用for...in循環會獲取到原型鏈上的可枚舉屬性,不過可以使用hasOwnProperty()方法過濾掉。
總結
以上是生活随笔為你收集整理的JavaScript 中 obj.hasOwnProperty(prop) 方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue3 echarts5 graph关
- 下一篇: 读javascript百炼成仙笑死笔记一