The hasOwnProperty returns true if the property is its own property and not inherited.
object.hasOwnProperty(prop)
Where prop is the name of the property to check.
In the example below, we define prop1 in the obj. Hence the hasOwnProperty returns true. But prop2 does not belong to obj, Hence it returns false.
const obj = {
prop1: '1'
};
obj.hasOwnProperty('prop1'); // true
obj.hasOwnProperty('prop2'); // false. Does not exists
The hasOwnProperty returns true only if the property is its own property. For Example, toString in the following code is the inherited property hence returns false.
var str = new String("Hello")
console.log(str.toString()) //Works
console.log(str.hasOwnProperty('toString')) //false
The hasOwnProperty method belongs to the Object.prototype. Hence it works only our object inherits from it.
When we create an object using object literal or constructor function, it always inherits from the Object.
But, you can also create an object without settings it prototype as shown below. In that case hasOwnProperty will not work
newObj = Object.create(null)
newObj.prop1="";
newObj.hasOwnProperty('prop1') //Uncaught TypeError: newObj.hasOwnProperty is not a functio
In that case, we can use the call method to invoke the hasOwnProperty and passing the object as its this.
newObj = Object.create(null)
newObj.prop1="";
console.log(({}).hasOwnProperty.call(newObj,"prop1")) //true
The JavaScript does not stop anyone from overriding the hasOwnProperty property down the prototype chain.
The code below declares the hasOwnProperty and always returns false. We can use the same workaround, we used in the previous section
const obj = {
prop1: '1',
hasOwnProperty() {
return false
}
};
//uses the hasOwnProperty declared in the obj
console.log(obj.hasOwnProperty('prop1')); // false
//Work around using the call method
console.log(({}).hasOwnProperty.call(obj,"prop1")) //true
Read More