简体   繁体   English

是否有一种jQuery方法只迭代对象自己的属性?

[英]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 . 我正在制作一个类似jQuery的小型库,有一件事让我感到奇怪的是$.each的行为。

In javascript we have a for...in loop: 在javascript中我们有一个for...in循环:

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. 例如,可以使用hasOwnProperty来了解这一点。 And jQuery could do that. 而jQuery 可以做到这一点。

But, when you pass an object to $.each , it behaves exactly like a for...in , iterating over inherited properties as well. 但是,当您将对象传递给$.each ,它的行为与for...in 完全相同 ,也会迭代继承的属性。 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 . 检查这个小提琴 ,看看它的实际效果,并在这里查看$.each的源代码。

So my question is, is there an object iteration method in jQuery that only includes own properties? 所以我的问题是,jQuery中是否有一个只包含自己属性的对象迭代方法? If not, should a library behave like this? 如果没有,库应该像这样吗?

Edit: Since jQuery does not do this, you can also answer if this is useful. 编辑:由于jQuery不这样做,你也可以回答这是否有用。 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. jQuery行为是有道理的,因为你总是可以选择在循环中添加hasOwnProperty检查 - 或者不是。

I can see that looping through inherited properties could be useful in some scenarios (cloning or sub-class or whatever you call it). 我可以看到循环继承属性在某些场景中可能很有用(克隆或子类或任何你称之为的东西)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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