Quantcast
Channel: What is the reason for var $this = this - Stack Overflow
Viewing all articles
Browse latest Browse all 7

Answer by Shaun for What is the reason for var $this = this

$
0
0

In actuality jQuery is a wrapper around the JavaScript DOM, both enhancing and simplifying it. Very briefly JQuery selectors return JQuery Object/s i.e.

var jQueryResults = $("article"); //Contains all article elements in the DOM as JQuery objects

However, selecting elements with Javascript returns HTML DOM elements i.e.

var normalResults = document.getElementsByTagName("article");//Contains all article elements in the DOM as HTML objects

The issues arise in that DOM objects do not provide the same functionality that JQuery objects provide.

Here is an event example which illustrates the difference:

$('.changeColorHover').hover(function() {    this.attr("style", "color:red");}); //Will not work as we are trying to call a JQuery method on a DOM object

With the above mentioned in mind the 'this' keyword is a DOM object and thus you are required to convert it to a jQuery object in order to utilise jQuery methods.

 $('.changeColorHover').hover(function() {        $(this).attr("style", "color:red"); }); //Will work since we have first converted the DOM object to a JQuery object

To sum up, the this keyword, allows you to access the object that called the event as this will give a reference to the object that raised the event. But, this is a DOM object, not a jQuery object. As a result, any of the jQuery methods you'd like to use aren't available, unless you convert it to a jQuery object.


Viewing all articles
Browse latest Browse all 7

Trending Articles