美文网首页
js属性对象的hasOwnProperty方法

js属性对象的hasOwnProperty方法

作者: 凡凡的小web | 来源:发表于2018-12-03 10:16 被阅读0次

Object的hasOwnProperty()方法返回一个布尔值,判断对象是否包含特定的自身(非继承)属性。

判断自身属性是否存在

varo =newObject();o.prop ='exists';functionchangeO(){  o.newprop = o.prop;deleteo.prop;}o.hasOwnProperty('prop');// truechangeO();o.hasOwnProperty('prop');// false

判断自身属性与继承属性

functionfoo(){this.name ='foo'this.sayHi =function(){console.log('Say Hi')  }}foo.prototype.sayGoodBy =function(){console.log('Say Good By')}letmyPro =newfoo()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'inmyPro)// true

遍历一个对象的所有自身属性

在看开源项目的过程中,经常会看到类似如下的源码。for...in循环对象的所有枚举属性,然后再使用hasOwnProperty()方法来忽略继承属性。

varbuz = {fog:'stack'};for(varnameinbuz) {if(buz.hasOwnProperty(name)) {        alert("this is fog ("+ name +") for sure. Value: "+ buz[name]);    }else{        alert(name);// toString or something else}}

注意 hasOwnProperty 作为属性名

JavaScript 并没有保护 hasOwnProperty 属性名,因此,可能存在于一个包含此属性名的对象,有必要使用一个可扩展的hasOwnProperty方法来获取正确的结果:

varfoo = {hasOwnProperty:function(){returnfalse;    },bar:'Here be dragons'};foo.hasOwnProperty('bar');// 始终返回 false// 如果担心这种情况,可以直接使用原型链上真正的 hasOwnProperty 方法// 使用另一个对象的`hasOwnProperty` 并且call({}).hasOwnProperty.call(foo,'bar');// true// 也可以使用 Object 原型上的 hasOwnProperty 属性Object.prototype.hasOwnProperty.call(foo,'bar');// true

原文 https://www.cnblogs.com/weiqinl/p/8683207.html

相关文章

网友评论

      本文标题:js属性对象的hasOwnProperty方法

      本文链接:https://www.haomeiwen.com/subject/zwwecqtx.html