开发者

Should I make a local variable $this when accessing $(this) multiple times?

Example:

$("#footer-create-nav li").click(function () {
    var $this = $(this);
    $this.addClass('footer-create-active');
    $this.siblings().removeClass('footer-create-active');
    return false;
}

vs how alot of my code开发者_运维技巧 looks:

$("#footer-create-nav li").click(function () {
    $(this).addClass('footer-create-active');
    $(this).siblings().removeClass('footer-create-active');
    return false;
}


It is a good practice to avoid recreating a jQuery object multiple times.

this represents a DOM object, and when passed to the $ or jQuery function, a new jQuery object is created every single time. Caching that object once in $this or any other variable name of your liking avoids having to recreate the object on each invocation of $(this). The benefits of this caching may depend on how many times you are calling $(this) and may be unnoticeable in most cases.

To get a better idea, test it out for yourselves.


You have another option. jQuery methods return the object they're operating on.

$(this).addClass("example")

would return the value of $(this).

So you could write your function as

$("#footer-create-nav li").click(function () {
    $(this).addClass('footer-create-active')
           .siblings().removeClass('footer-create-active');
    return false;
}

and only refer to this once without using another variable.


See Also

  • Question: jQuery chaining: Can everything be chained? When can we not chain?


Probably not. To put things in perspective, if a user triggered that function (by clicking) a thousand times on a single page, the speedup might balance out the additional download time incurred by the additional 20 bytes of JS code.

If you were doing a complex selector lookup in a tight loop, caching the result might be worthwhile. It definitely isn't in this case, though.


I can't explain it, but this jsperf appears to show that it is better to call $(this) each time...

http://jsperf.com/jquery-this-vs-this-vs-chain

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜