Check if a given object has a specified property. You can either use non-enumerable props or hasOwnProperty
.
Consider the below code -
|
|
We have defined a prototype that gets attached to any object. Therefore the prop defined by prototype is attached to the object as well.
What if you want to check all props in earth
?
|
|
Even when the object is empty, the awesomeness
prop rears it beautiful head.
We can avoid this incorrect reporting of prop against an object in two ways.
Use hasOwnProperty when checking for props in an object
Check for hasOwnProperty
before printing out the prop. Since awesomeness
does not satisfy the criteria it does not make the cut.
|
|
Use defineProperty
to set prop
Define prop against prototype using defineProperty
and set enumerable
to false
. This will suppress any unwanted behaviour.
|
|