Possible Duplicate:
How do I check if an object has a specific property in JavaScript?
I found the following snippet in Twitter's JavaScript files. Why do they need to call the hasOwnProperty
function to see dict
has the key
property? The for loop is running for each 'key' in 'dict' which means 'dict' has 'key'. Am I missing a point?
function forEach(dict, f) { for (key in dict) { if (dict.hasOwnProperty(key)) f(key, dict[key]); } }
The key difference is that in will return true for inherited properties, whereas hasOwnProperty() will return false for inherited properties.
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
Then no, you don't need to use the hasOwnProperty() . But the full control over the environment is not something you should count on. It's fine to drop the hasOwnProperty() only until someone somewhere redefines the Object type. Before or even after your script is started.
The hasOwnProperty() method returns true if the property is directly present in the object (not in its prototype chain). If an object is an Array, then the hasOwnProperty() method can check if an index is available (not empty) in the array.
Because if you don't, it will loop through every property on the prototype chain, including ones that you don't know about (that were possibly added by somebody messing with native object prototypes).
This way you're guaranteed only the keys that are on that object instance itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With