Short answer
Within a Event Handler (ex.: the function fn
in $(...).click(fn)
) the this
refers to an element of the FOD. This means that the most direct - and most performative - way to act on this element is to call 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) that 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>");
Already the $this
is a common variable, with nothing special. Often this name is agreed for the jQuery object containing the this
, and its main use is to avoid repeating the $(this)
several times (which brings a certain overhead unnecessary):
var id = this.id;
var $this = $(this); // Poderia ser "var elefante = $(this);" tanto faz...
if ( $this.hasClass("minhaClasse") )
$this.append("<p>Olá, Mundo!</p>");
Full answer
A "jQuery object" is a wrapper ("envelope"? ) over a list of objects. It was created with the intent 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, one 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 is an "array-like").
var $els = $([el1, el2, el3]);
$els.length; // 3
$els[1]; // el2
When you use $(...).each(fn)
, he calls the function fn
using each individual element to be traversed as the context of the function (i.e. the this
). Therefore, if your jQuery object has a list of elements, every iteration of the this
will be a "raw element".
And why is this relevant? Simple: every function that acts on a jQuery object - functions that you can find in $.fn
- takes as context the jQuery object itself, and then decides 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 make the two one: or obtainer a value of first element, or attribute 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 that we pass as argument to 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.
Here are the answers in English: http://stackoverflow.com/questions/3889570/what-is-the-difference-between-this-this-and-this
– Franchesco
@Earendul I had seen, but my English is not the best
– RodrigoBorth