如果多次使用$(this),是否应该在jQuery中缓存它? [英] Should I cache $(this) in jQuery if it is used more than once?

查看:97
本文介绍了如果多次使用$(this),是否应该在jQuery中缓存它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如果您多次使用选择器,则应该缓存该选择器的结果.一个例子是:

I know that you are supposed to cache the results of a selector if you use it more than once. An example would be:

var $selected = $('.some-selected-element');

process($selected);
doStuff($selected);

但是如果多次使用$(this)缓存,对性能有什么好处?

But is there any performance benefit to caching $(this) if it is used multiple times?

$('.some-selector').hover(function () {
    if (!$(this).hasClass('some-other-class')) {
        $(this).addClass('another-class');
    }
    process($(this));
}

推荐答案

是的,性能有所提高,因为它可以防止jQuery解释您的选择器.

Yes, there's a performance increase, because it prevents jQuery from having to interpret your selector.

这里是选择器的解释,以及您将忽略的内容. https://github.com/jquery/jquery/blob /master/src/core.js#L78-188

Here's the interpretation of a selector, and what you'll be bypassing. https://github.com/jquery/jquery/blob/master/src/core.js#L78-188

本质上,这部分

if ( selector.nodeType ) {
    this.context = this[0] = selector;
    this.length = 1;
    return this;
}

这篇关于如果多次使用$(this),是否应该在jQuery中缓存它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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