脚本宝典收集整理的这篇文章主要介绍了js属性对象的hasOwnProperty方法的使用,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
Object的hasOwnPRoPErty()方法返回一个布尔值,判断对象是否包含特定的自身(非继承)属性。
VAR o = new Object(); o.prop = 'exists'; function changeO() { o.newprop = o.prop; delete o.prop; } o.hasOwnProperty('prop'); // true changeO(); o.hasOwnProperty('prop'); // false
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) // true
在看开源项目的过程中,经常会看到类似如下的源码。for...in循环对象的所有枚举属性,然后再使用hasOwnProperty()方法来忽略继承属性。
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 } }
JavaScript 并没有保护 hasOwnProperty 属性名,因此,可能存在于一个包含此属性名的对象,有必要使用一个可扩展的hasOwnProperty方法来获取正确的结果:
var foo = { hasOwnProperty: function() { return false; }, 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
到此这篇关于js属性对象的hasOwnProperty方法的使用的文章就介绍到这了,更多相关js hasOwnProperty内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本宝典!
以上是脚本宝典为你收集整理的js属性对象的hasOwnProperty方法的使用全部内容,希望文章能够帮你解决js属性对象的hasOwnProperty方法的使用所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。