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

别等时光非礼了梦想. 提交于 2019-12-10 15:22:20

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/13688337/is-there-a-jquery-way-of-iterating-over-an-objects-own-properties-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!