Home » jQuery » Important Tips on jQuery - Difference between this, $this and $(this)
Important Tips on jQuery - Difference between this, $this and $(this)
Let us understand the difference between this, $this and $(this) with an example. Consider the following code:
Here we are looping over a bunch of div’s using each(). Once you are inside the loop, this refers to the DOM element which is not a jQuery object. So to make it a jQuery object and to run jQuery methods on it, we do $(this).
Now look at this statement: var $this = $(this);
If you’re going to reference the DOM element multiple times in the code, which we are doing in our example; then for performance sake, you should get a jQuery reference to it and then save that to a variable. Here $this is that variable. This is also called as caching the selector as it is expensive to run the jQuery function $(this) each time. So storing the output in a variable allows you to re-use the selector over and over, without calling the jQuery function again.
Note: Don’t get confused with $this. You can call it anything you like. I usually refer to variables that contain jQuery objects as $variablename.
0 comments :
Post a Comment