简体   繁体   中英

Is there a jQuery way of iterating over an objects own properties only?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM