Short answer
Within an event handler (eg, the function fn
in $(...).click(fn)
) this
refers to a DOM element. This means that the most direct - and most performative - way of acting on this element is by calling methods on it:
var id = this.id;
if ( (" " + this.className + " ").replace(/[\n\t]/g, " ").indexOf("minhaClasse") > -1 ) {
var p = document.createElement("p");
p.innerHTML = "Olá, Mundo!";
this.appendChild(p);
}
The use of $(this)
encasula ( wraps ) this element in a jQuery object , allowing you to use the various functions provided by this library and its plugins. It's a little less efficient, but often much more convenient:
var id = $(this).prop("id");
if ( $(this).hasClass("minhaClasse") )
$(this).append("<p>Olá, Mundo!</p>");
Since $this
is a common variable, with nothing special. Often this name is convened for the jQuery object containing this
, and its main use is to avoid repeating $(this)
several times (which brings an unnecessary overhead ): / p>
var id = this.id;
var $this = $(this); // Poderia ser "var elefante = $(this);" tanto faz...
if ( $this.hasClass("minhaClasse") )
$this.append("<p>Olá, Mundo!</p>");
Complete answer
A "jQuery object" is an wrapper ("envelope"?) over a list of objects. It was created with intention to be used with DOM elements, but at first you can encapsulate anything in it:
$([1,2,3]).each(function() { /* aqui o "this" é um elemento da lista */ });
$(); // Vazio
$(el); // Um elemento
$([el1, el2, el3]); // Vários elementos
$(strSeletor); // zero, um ou vários elementos (depende do que o seletor "pegar")
Given a jQuery object, you can find out how many elements it has using length
, and access any individual element using [indice]
. That is, it behaves as if it were an array (i.e. it's an array-like).
var $els = $([el1, el2, el3]);
$els.length; // 3
$els[1]; // el2
When you use $(...).each(fn)
, it calls the fn
function using each individual element to be traversed as the context of function (ie this
). So if your jQuery object has a list of elements, at each iteration of the loop the this
will be a "raw" element.
And why is this relevant? Simple: any function that acts on a jQuery object - functions that you can find in $.fn
- get the jQuery object as its context, and then decide what to do with it:
$.fn.meuPlugin = function() {
var $this = this; // Aqui this já é um objeto jQuery
};
In general, the most common functions we know of do either: get a first value, or assign a value to all elements :
$.fn.meuPlugin = function(argumentoOpcional) {
if ( argumentoOpcional === undefined ) { // get
return this[0].umValor;
}
else { // set
return this.each(function() { // O this aqui fora é um objeto jQuery
this.umValor = argumentoOpcional; // O this aqui dentro é um elemento individual
});
}
};
$(meuSeletor).meuPlugin(); // Obtém o valor do primeiro elemento encontrado
$(meuSeletor).meuPlugin(42); // Atribui o valor 42 a todos os elementos encontrados
Because of this - because plugins make common use of each
or map
- is that the functions we pass as arguments for these plugins usually receive the raw element as context. This organization allows the same function to work without distinction between zero, one, or multiple elements - simplifying the code for the end user.