Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$this vs $(this) in jQuery

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 ...

like image 424
larryq Avatar asked Sep 12 '11 15:09

larryq


People also ask

What is $( this used for in jQuery?

Explanation: The $(this) selector is used to select current HTML elements.

What is $( this in JS?

$(this) is a jQuery object and this is a pure DOM Element object. See this example: $(".test"). click(function(){ alert($(this). text()); //and alert(this.

Is vanilla JavaScript faster than jQuery?

It is said that jQuery is better for DOM manipulation than Javascript, however, after monitoring both of their performances, vanilla JS was found to be faster than jQuery.


2 Answers

$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.

like image 65
Joe Avatar answered Oct 01 '22 17:10

Joe


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.

like image 24
ThiefMaster Avatar answered Oct 01 '22 16:10

ThiefMaster