Object的hasOwnProperty()
方法返回一个布尔值,判断对象是否包含特定的自身(非继承)属性。this
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()
方法来忽略继承属性。prototype
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 } }
hasOwnProperty
做为属性名JavaScript 并无保护 hasOwnProperty
属性名,所以,可能存在于一个包含此属性名的对象,有必要使用一个可扩展的hasOwnProperty
方法来获取正确的结果:code
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
参考连接
[完]对象