Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  14] [ 5]  / answers: 1 / hits: 45250  / 12 Years ago, thu, october 4, 2012, 12:00:00

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]);
}
}

More From » javascript

 Answers
13

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.


[#82749] Wednesday, October 3, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
allans

Total Points: 336
Total Questions: 120
Total Answers: 119

Location: Peru
Member since Mon, Jun 6, 2022
2 Years ago
;