是否有jQuery方法只迭代对象自己的属性? [英] Is there a jQuery way of iterating over an objects own properties only?

查看:162
本文介绍了是否有jQuery方法只迭代对象自己的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个类似jQuery的小型库,有一点让我感到奇怪的是 $。每个

I'm making a small jQuery-like library, and one thing striking me odd is the behavior of $.each.

在javascript中我们有 for ... in 循环:

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.

可以使用 hasOwnProperty 。并且jQuery 可以这样做。

但是,当你将一个对象传递给 $。每个,它在中的行为完全就像一样,迭代继承的属性。它也应该稍微慢一些,并且需要输入更多的字符。

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.

所以我的问题是,有吗jQuery中的 object 迭代方法,只包含自己的属性?如果没有,库是否应该像这样?

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?

编辑:由于jQuery不这样做,你也可以回答它是否有用。我的意思是,我看不到自己想要迭代原型属性,但也许我错过了一些东西。

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.

推荐答案

jQuery行为是有道理的,因为你总是可以选择在循环中添加hasOwnProperty检查 - 或者不是。

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

这篇关于是否有jQuery方法只迭代对象自己的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆