I'm making a small jQuery-like library, and one thing striking me odd is the behavior of $.each
.
In javascript we have a for...in
loop:
for (var key in obj) {
console.log(key + ': ' + obj[key]);
}
The problem with this, is that it will iterate over inherited properties as well, that is, properties coming from the object constructor's prototype.
One can know this using hasOwnProperty
, for example. And jQuery could do that.
But, when you pass an object to $.each
, it behaves exactly like a for...in
, iterating over inherited properties as well. It also should be marginally slower, and requires a few more characters to type.
Check this fiddle to see it in action and look here for the source code of $.each
.
So my question is, is there an object iteration method in jQuery that only includes own properties? If not, should a library behave like this?
Edit: Since jQuery does not do this, you can also answer if this is useful. I mean, I cannot see myself wanting to iterate over prototype properties, but maybe I'm missing something.
The jQuery behavior makes sense, as you can always choose to add the hasOwnProperty check in the loop - or not.
I can see that looping through inherited properties could be useful in some scenarios (cloning or sub-class or whatever you call it).