As other's have said, extending Object.prototype
might not be a good idea if your code has to play nice with code written by people ignorant of hasOwnProperty()
.
Anyway, there are three 'correct' ways I know of to check if a property is available:
obj.hasOwnProperty(name)
checks if a property with given name exists in the object.
name in obj
additionally includes properties inherited via an object's prototype chain.
typeof obj[name] !== 'undefined'
will additionally evaluate to false
if the property is present but has been set to undefined
.
Some non-JS object's (e.g. window.external
in IE) might not implement hasOwnProperty()
, so one of the other checks has to be used.