缓存或不缓存jQuery中的$(this) [英] To cache or not to cache $(this) in jQuery

查看:89
本文介绍了缓存或不缓存jQuery中的$(this)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当选择器 $(this)时,创建和重用引用是否会显着提高性能?

Does creating and reusing a reference increase performance appreciably when the selector is $(this)?

I当我在同一范围内多次使用相同的选择器时,为我的jQuery选择器创建引用。以下更有效

I create references for my jQuery selectors when I use the same selector multiple times in the same scope. The following is more efficient

    var jSel = $('div.some_class input.some_other_class');
    some_function1(jSel);
    some_function2(jSel);

比这个

    some_function1($('div.some_class input.some_other_class'));
    some_function2($('div.some_class input.some_other_class'));

但是如果选择器只是 $(this)其中这个是jQuery方法中的dom元素。我是否需要创建对 $(this)的引用并重用该引用,或者我可以创建多个 $(this)选择器并期望获得类似的表现?

But what if the selector is simply $(this) where this is a dom element inside a jQuery method. Should I bother to create a reference to $(this) and reuse the reference or can I create multiple $(this) selectors and expect similar performance?

以下是

    var jSel = $(this);
    some_function1(jSel);
    some_function2(jSel);

明显快于以下情况?

    some_function1($(this));
    some_function2($(this));


推荐答案


以下是显着的比以下更快?

Is the following significantly faster than the following?

。它在显微镜下更快;在几微秒的范围内。

No. It is microscopically faster; in the realms of just a few microseconds.

这是否会阻止您将结果分配给变量并使用它? 即可。使用变量可以为这个提供更多含义,并且可以更容易输入。另外,如果你不想在 $(this)上操作,而是想要 $(this).next(),你必须在一个地方改变它而不是 n

Does that stop you assigning the result to a variable and using that? No. Using a variable can give more meaning to what this is, and can be easier to type. Plus, if you stopped wanting to operate on $(this), and instead wanted $(this).next(), you have to change it in one place instead of n.

你会发现jQuery构造函数是高度已经过优化,可以接受单个DOM元素作为参数。以下是执行的确切代码当你打电话给 $(DOMElement)创建jQuery对象后,当然):

You'll find the jQuery constructor is highly optimized for accepting a single DOM element as a parameter. The following is the exact code that gets executed when you call $(DOMElement) (after the jQuery object has been created, of course):

var match, elem, ret, doc;

// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
    return this;
}

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

// Handle lots of other param types, but we hit the above one, so we've stopped now...

这篇关于缓存或不缓存jQuery中的$(this)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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