Question:
I always used $(this)
regardless of the situation and it always worked. Rarely have I had to use one of the others and these times I did it because of someone's guidance and not because I knew exactly what I had to do.
- So what's the difference between the 3 types of this?
- When should I use one and when should I use another?
- Does it somehow change the performance of the code?
Answer:
Simple version:
this
– simple object. Nodejs DOM, window
or global
element
$this
– a simple variable, it can have any value
$(this)
– jQuery object with methods that jQuery provides
Longer version:
-
this
when pointing to an element
When we use this
inside for example an event handler we are referring to the raw, simple, original element.
Example:
$('#minhadiv').click(function(){ alert(this.id)}); // dá: "minhadiv" quando clicado
this
when in global scope
When we use this
in global space we are referring to window
or global
if it is in NodeJS
(function(glob){
glob.variavelXPTO = '2014!';
})(this);
alert(variavelXPTO); // dá: 2014 - note que está no escopo global
$this
is a simple variable
$this
is used as a simple variable. Very common to use $this = $(this);
which is a way to store the jQuery object reference in scopes where the this
is other, such as inside an Ajax call or inside a Class.
var $this = 'that';
alert($this); // dá: "that" - aqui o $this guarda simplesmente uma string
var $this = $('#minhadiv');
alert($this.attr('id')); // dá: "minhadiv", ou seja retorna a id via método .attr() do jQuery
$(this)
isthis
but with jQuery powers!
In order to use jQuery methods on objects, you must pass the object as a parameter to the jQuery $()
. Then the function returns a new object with the methods that jQuery makes available. It can be used in arrays, for example $(['foo', 'bar']).each(minhaFn);
Example using something from the first example:
$('#minhadiv').click(function(){ alert(this.id)}); // dá: minhadiv
$('#minhadiv').click(function(){ alert($(this).id)}); // dá erro
$('#minhadiv').click(function(){ alert($(this).attr('id'))}); // dá: minhadiv
$('#minhadiv').click(function(){
$(this).closest('.main'); // aqui vai procurar o elemento pai com a classe "main"
});
To do the same as $(this).closest('.main');
does but in pure JavaScript, ie using this
had to be something like:
var closestByClass = function(el, clz) {
while(el && el != document) {
var p = el.parentNode;
var classes = ((p && p.className) || '').split(/\s+/);
if (arrayIncludes(classes,clz)) {
return p;
}
else {
el = p;
}
}
return null;
};
Which takes more work to write 😛
To remove the original element from inside a jQuery object we can use index, ie var divs = $('div');
gives an array-like object where divs[0] is the first div, raw. would be the same as with this
. You can also use .get()
to fetch the raw, simple object of the jQuery object