JavaScript: Difference between “this”, “$this” and “$(this)”

In the context of jQuery, this is the object upon which a method was called. $this is indeed a poorly named variable with no special meaning. $(this) passes this to jQuery, which will return a jQuery object associated with whatever this is, as long as this is a DOM object.

In jQuery event handler:

  • this – a DOM element you assigned the event handler to
  • $(this) – a jQuery object created from that element
  • $this – typically, a variable holding the result of $(this)

More generally:

  • this inside a function refers to the object or primitive the function is called on. When a function is used as a constructor, it refers to the new object being constructed. Outside of any function this refers to the global object (window in non-strict mode).

    You can find a good detailed explanation on MDN.

  • $this is a variable name. In JavaScript variable names can start with $. Some like to use it as a prefix for variables containing jQuery objects:

  • $(this) is a function call, where $ is a function name, and this is its argument:

    $ doesn’t have any special meaning per se. But jQuery defines the $() function as a shorthand for jQuery(). Depending on its arguments, this function can do many different things.

$ is poorly named for two main reasons. Firstly, it tells you nothing about what the function does, that half a dozen libraries all use it for different things doesn’t help as people who have to come in to deal with code then have to figure out what library is being used (it is made worse when multiple libraries are used togehter). Secondly, ECMA-262 3rd edition states “The dollar sign is intended for use only in mechanically generated code”, this is a good way to stop such code conflicting with handwritten code. As for saving bandwidth, that is what a minifier is for.

  • $this is usually used to have a copy of the this object in the current scope. For example with var $this = this; you can use the variable $this anywhere in the current scope and always be able to reference that object that would otherwise change if simply referenced with this… I personally dislike the $this naming convention and prefer something like var parentScope

  • $(this) is a function (var $ = function(){}) used by some frameworks like jQuery or PrototypeJs. The reason it is used is because $ is very easy to type instead of someLongFunctionName and because it is usually called many times in the code it’s easier to have it be as short as possible

Leave a Reply

Your email address will not be published. Required fields are marked *