Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing "$(this)" multiple times within the same function [duplicate]

Tags:

jquery

Possible Duplicate:
Caching $(this) in jQuery is a best practice?

I am curious, within the same function, when $(this) is called multiple times does it incur additional overhead for constructing the jQuery object in the subsequent calls? In other words, is $(this) cached the first time it's called? If not, would it be a better practice to store $(this) in a variable and use that variable when $(this) is needed subsequently?

like image 850
tamakisquare Avatar asked Apr 27 '26 07:04

tamakisquare


2 Answers

$() is the jQuery constructor function.

this is a reference to the DOM element of invocation.

so basically, in $(this), you are just passing the this in $() as a parameter so that you could call jQuery methods and functions.

http://www.learningjquery.com/2007/08/what-is-this

good figures: http://jsperf.com/jquery-this-vs-this-vs-chain/2

You usually use var $this = $(this); to avoid creating a new jQuery object more often than necessary. In case of the code below you only create one object instead of two/four. It is completely unrelated to chainability.

this in javascript (usually) represents a reference to the object that invoked the current function.

Generally the purpose of storing $(this) in a local variable is to prevent you from calling the jQuery function $() multiple times, caching a jQueryized this should help efficiency if you have to use it multiple times.

$ is simply a valid variable name character and is used as the first character of a variable name usually to queue the programmer that it is a jQuery object already (and has the associated methods/properties available).

$this vs $(this) in jQuery

like image 97
Tats_innit Avatar answered Apr 29 '26 21:04

Tats_innit


I've seen this construct used quite often:

var someFunc = function () {
    var that = $(this);
    // you could also cache like var $this = $(this);

    // do stuff here...
};

Each time you call $() there would be some overhead in making the call but not much. I don't think it would be noticeable if you didn't cache $(this). See SO entry on jquery cache of $(this)

like image 20
sinemetu1 Avatar answered Apr 29 '26 21:04

sinemetu1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!