将 jQuery 对象存储在变量中会不会有什么缺点?

发布于 2024-08-01 13:57:40 字数 490 浏览 2 评论 0原文

我最近刚刚问了有关 jQuery 更改的以下问题:

是否有一种首选方法来格式化 jQuery 链以使其更具可读性?

许多人回复了建议,也许我减少了语句中的链接量,而是将对象存储在保存变量中,这对我来说很有意义。

然而,我的理解是,链中的对象已经保存在堆栈中(某种程度),因此将结果缓存/存储在变量中是否无法有效地重新存储它,使用更多内存?

对其中一篇文章的评论似乎表明可能不会对性能造成太大影响(如果有的话),因此如果它更具可读性,我很乐意按照建议进行缓存。

而且,如果我们使用缓存,这不会开始限制 .end().andSelf() 的用处吗?

I've just recently asked the folloiwng question with regard to jQuery chaning:

Is there a preferred way of formatting jQuery chains to make them more readable?

A number of people replied with the suggestion that maybe I reduced the amount of chaining within the statement, and instead stored objects in holding variables, which makes sense to me.

However, my understanding is that the objects within a chain are already held on a stack (of sorts), so is the caching/storing of the results in a variable not effectively re-storing it, using more memory?

A comment on one of the posts seemed to indicate that there might not be too much of a performance hit (if any), so I would be happy to cache as suggested if it would be much more readable.

And also, if we are using caching, does this not then start limiting the usefulness of .end() and .andSelf()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

始于初秋 2024-08-08 13:57:40

对象通常存储为引用 - 指向内存中位置的指针。 两个保存同一个对象的变量不会复制该对象的所有数据 - 它们只是都保存指向内存中实际对象数据所在的同一位置的指针。 因此,将对象存储在变量中根本不会对性能造成太大影响; 没什么重要的。

Objects are generally stored as references - pointers to locations in memory. Two variables both holding the same object don't duplicate all of the object's data - they just both hold pointers to the same location in memory where the actual object data is located. Thus, storing the object in a variable won't have much of a performance hit at all; nothing significant.

淑女气质 2024-08-08 13:57:40

添加@Dav 的答案,有时将 jquery 对象存储在变量中将是一件好事。 经典示例:

$('#something div').each( function() {
    $(this).css({'background-color':'#afa'});
    // do some stuff;
    $(this).slideDown('fast');
}

更好的方法:

$('#something div').each( function() {
    var $this = $(this);
    $this.css({'background-color':'#afa'});
    // do some stuff;
    $this.slideDown('fast');
}

这样您就可以避免在调用 $创建 jquery 对象。

Adding to @Dav's answer, there are times when storing jquery objects in variables will be a good thing. Classic example:

$('#something div').each( function() {
    $(this).css({'background-color':'#afa'});
    // do some stuff;
    $(this).slideDown('fast');
}

Better way:

$('#something div').each( function() {
    var $this = $(this);
    $this.css({'background-color':'#afa'});
    // do some stuff;
    $this.slideDown('fast');
}

This way you avoid creating jquery objects whenever you call $.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文