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 ...
Explanation: The $(this) selector is used to select current HTML elements.
$(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.
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.
$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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With