Paul
Paul

Reputation:

jQuery $this vs $(this) in plugin development

I was wondering why in so many jquery plugins $(this) is set to be pointing at $this, here is an example, if i have the following two plugins included on a page:

(function($) {
   jQuery.fn.pluginOne = function() {
      return this.each(function() {
         $this = $(this); <--
         alert($this);
      });
   };
})(jQuery)

(function($) {
   jQuery.fn.pluginTwo = function() {
      return this.each(function() {
         $this = $(this); <--
         alert($this);
      });
   };
})(jQuery)

When i call both plugins on dom ready:

$(document).ready({
   $('.myClass').pluginOne();
   $('.myOtherClass').pluginTwo();
});

The first plugin will get $this from the second plugin... while it i point $(this) to a local var:

(function($) {
   jQuery.fn.pluginTwo = function() {
      return this.each(function() {
         var trigger = $(this); <--
         alert(trigger);
      });
   };
})(jQuery)

everything works at it should, of course...

So my question is... when should I use $this?

Thanks

Upvotes: 8

Views: 6563

Answers (3)

DisgruntledGoat
DisgruntledGoat

Reputation: 72560

$ is a legitimate character for variable and function names in Javascript. That might be confusing if you're coming from PHP where $ is used to signify a variable only (took me a while to realise).

  • In jQuery, $ is an alias for the function jQuery, which is the main function that handles DOM selection. $("#header ul.menu") is the same as jQuery("#header ul.menu"). $ is simply used for brevity.

  • this is a special term in Javascript (not jQ) meaning the current element (in forms you might see this.submit() for example).

  • $(this) means "call the jQuery function with Javascript's this".

  • $this is simply a variable, since $ is a valid character. You can set $this to any value you like and it's completely unrelated to Javascript's this. In general I'd suggest NOT using $ for variable names to avoid confusion with the jQuery function. However, it may be useful to use $var to denote jQuery objects as opposed to normal Javascript variables.

Upvotes: 9

Russ Cam
Russ Cam

Reputation: 125518

if you are performing a number of different commands with an element wrapped in a jQuery object, then it is more performant to get the element (as a wrapped set) only once and store that in a local variable

var $this = $(this);
// then use $this in your function. 

Note the use of var to locally scope $this

Upvotes: 2

redsquare
redsquare

Reputation: 78677

$this is a standard people use to cache the actual jQuery object $(this) in a variable.

You can call it what you wish, some people like to refer to it as $self.

e.g

var $self = $(this)

It just helps when you are looking at the code to recognize that it is a jQuery object rather than a normal dom object.

It performs better as you only create one instance of the jQuery variable.

Upvotes: 12

Related Questions