$this vs $(this) in jQuery

JavascriptJquery

Javascript Problem Overview


I've seen some discussions on SO regarding $(this) vs $this in jQuery, and they make sense to me. (See discussion here for an example.)

But what about the snippet below, from the jQuery website plugin tutorial showing how chainability works?

(function ($) {

    $.fn.lockDimensions = function (type) {

        return this.each(function () {

            var $this = $(this);

            if (!type || type == 'width') {
                $this.width($this.width());
            }

            if (!type || type == 'height') {
                $this.height($this.height());
            }

        });

    };
})(jQuery);

What does $this represent above? Just when I think I have it figured out ...

Javascript Solutions


Solution 1 - Javascript

$this is just an ordinary variable. The $ character is a valid character in variable names, so $this acts the same as any other non-reserved variable name. It's functionally identical to calling a variable JellyBean.

Solution 2 - Javascript

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.

You could also call it that, $thi$ or anything else (don't use the latter one though, it's ugly :p) as $ is just a simple character in JavaScript, exactly like a-z are.

Solution 3 - Javascript

this in javascript (usually) represents a reference to the object that invoked the current function. This concept is somewhat fuzzied a bit by jQuery's attempts to make the use of this more user friendly within their .each() looping stucture.

outside the .each(), this represents the jQuery object that .lockDimensions is invoked by.

inside the .each() it represents the current iterated DOM object.

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 question is actually unrelated to chain-ability, but to maintain chain-ability you should return this so that other function calls can be added, and maintain the meaning of this in those calls as well.

Solution 4 - Javascript

you may have overlooked this line:

var $this = $(this);

Here, $this is just a variable that holds the value of $(this). You can use it interchangeably with $(this) with the benefit that you aren't doing the same lookup over and over.

Solution 5 - Javascript

$this is simply a local variable, named that way to remind you of $(this). It saves the work of creating the jQuery version of this, and you can use it a number of times.

Solution 6 - Javascript

$this is just a local copy of this wrapped in jQuery.

In the long term, keeping a local copy rather than wrapping this each time it is needed is much more efficient.

Solution 7 - Javascript

$this = $(this) is a way to cache the jQuery object. It is expensive to run the jQuery function each time, so storing the output allows you to re-use the selector over and over again without calling jQuery function again.

Solution 8 - Javascript

It just fills $this variable with $(this), so you do not have to lookup for $(this) element every call. It has better performance

var $this = $(this);

Solution 9 - Javascript

 $this = $(this)

which means that you are assigning the current object to a variable named $this. It is not a keyword. > It is just a variable name.

Solution 10 - Javascript

It's quite simple: $this = $(this). It's just a shorthand used in the scope of the inner function. The dollar sign is just a character in this case, it doesn't refer to jQuery at all. It might just as well have been named _this or xthis, the $ is just a reminder of what the variable contains.

It may seem pointless, but it eliminates three redundant method invocations (the $() function isn't free) so it is most likely used there for performance reasons.

Solution 11 - Javascript

Inside $.fn.lockDimensions, this is the jQuery object that had lockDimensions called on it.

Inside the .each, this now references the DOMElement in the current iteration of the loop. $(this) wraps the DOMElement in a jQuery object, and var $this = $(this); is just saving $(this) in a variable called $this, so the jQuery constructor doesn't need to be called multiple times (if you were to use $(this) instead).

Solution 12 - Javascript

$ sign is usually used before variable names in JavaScript to differentiate between general value and jQuery object. So here $this just gets the value of $(this) which returns jQuery object of this. $ is just a part of valid variable name.

Solution 13 - Javascript

$this is a variable named $this containing a reference to $(this). A bit pointless IMO.

Solution 14 - Javascript

I want to jump in here, even though I do not have expert jQuery skills.

Countless times I see lines of code or concepts similar to:

var $this = $(this);

So I do a rewrite of it similar to:

var $jims_this = $(this);

And test it. Also I do this to clear up any confusion I might have.

Here is another example of similar poorly explained code:

 <style>
    a.a { font-weight: bold; }
 </style>

Next, add the addClass call to your script:

  $("a").addClass("a");

This does work but it is confusing. It could have been written as:

<style>
a.my_bold_class { font-weight: bold; }
</style>

 $("a").addClass("my_bold_class");

Jim

Solution 15 - Javascript

You have wandered into the realm of javascript scope and closure.

For the short answer:

this.bar()

is executed under the scope of foo, (as this refers to foo)

var barf = this.bar;
barf();

is executed under the global scope.

this.bar basically means:

execute the function pointed by this.bar, under the scope of this (foo). When you copied this.bar to barf, and run barf. Javascript understood as, run the function pointed by barf, and since there is no this, it just runs in global scope.

To correct this, you can change

barf();

to something like this:

barf.apply(this);

This tells Javascript to bind the scope of this to barf before executing it.

For jquery events, you will need to use an anonymous function, or extend the bind function in prototype to support scoping.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlarryqView Question on Stackoverflow
Solution 1 - JavascriptJoeView Answer on Stackoverflow
Solution 2 - JavascriptThiefMasterView Answer on Stackoverflow
Solution 3 - JavascriptjondavidjohnView Answer on Stackoverflow
Solution 4 - JavascriptevanView Answer on Stackoverflow
Solution 5 - JavascriptNed BatchelderView Answer on Stackoverflow
Solution 6 - JavascriptJustin NiessnerView Answer on Stackoverflow
Solution 7 - JavascriptBilly MoonView Answer on Stackoverflow
Solution 8 - JavascriptgenesisView Answer on Stackoverflow
Solution 9 - JavascriptSudheer KumarView Answer on Stackoverflow
Solution 10 - JavascriptJens RolandView Answer on Stackoverflow
Solution 11 - Javascriptgen_EricView Answer on Stackoverflow
Solution 12 - JavascriptMuhammad UsmanView Answer on Stackoverflow
Solution 13 - JavascriptspenderView Answer on Stackoverflow
Solution 14 - Javascriptjim difView Answer on Stackoverflow
Solution 15 - JavascriptBhupendra JhaView Answer on Stackoverflow