The hasOwnProperty() method of objects returns a boolean indicating whether the object cnotains a specific own (non-inherited) property.
Checking for Own Properties
var obj = new Object();
obj.property = 'exists';
function modifyObj() {
obj.newProperty = obj.property;
delete obj.property;
}
obj.hasOwnProperty('property'); // true
modifyObj();
obj.hasOwnProperty('property'); // false
Distinguishing Own and Inherited Properties
function Constructor() {
this.identifier = 'Constructor'
this.greet = function () {
console.log('Hello')
}
}
Constructor.prototype.farewell = function () {
console.log('Goodbye')
}
let instance = new Constructor()
console.log(instance.identifier) // Constructor
console.log(instance.hasOwnProperty('identifier')) // true
console.log(instance.hasOwnProperty('toString')) // false
console.log(instance.hasOwnProperty('hasOwnProperty')) // false
console.log(instance.hasOwnProperty('greet')) // true
console.log(instance.hasOwnProperty('farewell')) // false
console.log('farewell' in instance) // true
Iterating Over a Object's Own Properties
When examining open-source code, you frequently encounter patterns like this. The for...in loop iterates through all enumerable properties of an objectt, followed by a hasOwnProperty() check to exclude inherited properties.
var buz = {
fog: 'stack'
};
for (var key in buz) {
if (buz.hasOwnProperty(key)) {
alert("this is fog (" + key + ") for sure. Value: " + buz[key]);
}
else {
alert(key); // toString or other inherited properties
}
}
Handling hasOwnProperty as a Property Name
JavaScript does not protect the hasOwnProperty property name, so it might exist as a property in objects that could interfere with normal behavior:
var example = {
hasOwnProperty: function() {
return false;
},
content: 'Here be dragons'
};
example.hasOwnProperty('content'); // Always returns false
// To avoid issues, use the original hasOwnProperty method from the prototype
// Call another object's hasOwnProperty with proper context
({}).hasOwnProperty.call(example, 'content'); // true
// Alternatively, use the hasOwnProperty from Object's prototype
Object.prototype.hasOwnProperty.call(example, 'content'); // true