js属性对象的hasOwnProperty方法的使用
Object的hasOwnProperty()方法返回一个布尔值,判断对象是否包含特定的自身(非继承)属性。
判断自身属性是否存在
varo=newObject(); o.prop='exists'; functionchangeO(){ o.newprop=o.prop; deleteo.prop; } o.hasOwnProperty('prop');//true changeO(); o.hasOwnProperty('prop');//false
判断自身属性与继承属性
functionfoo(){ this.name='foo' this.sayHi=function(){ console.log('SayHi') } } foo.prototype.sayGoodBy=function(){ console.log('SayGoodBy') } letmyPro=newfoo() 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'inmyPro)//true
遍历一个对象的所有自身属性
在看开源项目的过程中,经常会看到类似如下的源码。for...in循环对象的所有枚举属性,然后再使用hasOwnProperty()方法来忽略继承属性。
varbuz={ fog:'stack' }; for(varnameinbuz){ if(buz.hasOwnProperty(name)){ alert("thisisfog("+name+")forsure.Value:"+buz[name]); } else{ alert(name);//toStringorsomethingelse } }
注意hasOwnProperty作为属性名
JavaScript并没有保护hasOwnProperty属性名,因此,可能存在于一个包含此属性名的对象,有必要使用一个可扩展的hasOwnProperty方法来获取正确的结果:
varfoo={ hasOwnProperty:function(){ returnfalse; }, bar:'Herebedragons' }; foo.hasOwnProperty('bar');//始终返回false //如果担心这种情况,可以直接使用原型链上真正的hasOwnProperty方法 //使用另一个对象的`hasOwnProperty`并且call ({}).hasOwnProperty.call(foo,'bar');//true //也可以使用Object原型上的hasOwnProperty属性 Object.prototype.hasOwnProperty.call(foo,'bar');//true
参考链接
到此这篇关于js属性对象的hasOwnProperty方法的使用的文章就介绍到这了,更多相关jshasOwnProperty内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!