Overview
hasOwnProperty() method is used to determine whether an object contains the specified own property.
Grammar
obj.hasOwnProperty(prop)
Parameters
•prop
•The name of the attribute to detect.
Description
All objects that inherit Object.prototype will inherit the hasOwnProperty method from the prototype chain. This method can be used to detect whether an object contains specific own properties. Unlike the in operator, this method will ignore those from the prototype. Properties inherited from the chain.
Example
Example 1: Use the hasOwnProperty method to determine whether an object contains specific own properties
The following example checks whether object o contains its own attribute prop:
Example 2: The difference between own properties and inherited properties
The following example demonstrates the difference between the hasOwnProperty method's treatment of its own properties and inherited properties:
The following example demonstrates how to ignore inherited properties when traversing all properties of an object. Note that the for..in loop here will only traverse enumerable properties. This is usually what we want. Use Object.getOwnPropertyNames directly. () method can also achieve similar needs.
If an object has its own hasOwnProperty method, the method with the same name on the prototype chain will be shadowed: