What is the difference between $(this) and $this and this?

Asked

Viewed 3,927 times

51

I’ve always used the $(this) independent of the situation and always worked. Rarely have I had to use one of the others and on those occasions I did it for someone’s guidance and not for knowing exactly what I had to do.

  • So what’s the difference between the 3 types of this?
  • When I should wear one and when I should wear another?
  • Somehow changes the code performance?
  • Here are the answers in English: http://stackoverflow.com/questions/3889570/what-is-the-difference-between-this-this-and-this

  • 1

    @Earendul I had seen, but my English is not the best

3 answers

61


Simple version:

this - simple object. DOM element, window or global nodejs
$this - a simple variable, can have any value
$(this) - jQuery object with methods that jQuery provides

Longer version:

  • this when pointing out an element

When we use this within for example an Event Handler we are referring to the raw element, simple, original.

Example:

$('#minhadiv').click(function(){ alert(this.id)}); // dá: "minhadiv" quando clicado
  • this when in the overall scope

When we use the this in the 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

The $this is used as a simple variable. Very common use $this = $(this); which is a way to store reference to jQuery object in scopes where the this is another, as within an Ajax call or within 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) is this but with powers jQuery!

In order to use jQuery methods on objects you have to pass the object as jQuery function parameter $(). Then the function returns a new object with the methods that jQuery provides. 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 the 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;
  };

That gives more trouble to write :P

To remove the original element from inside a jQuery object we can use index, i.e. var divs = $('div'); gives an array-like object where Divs[0] is the first div, raw. would be the same as with this. Can also be used .get() to fetch the raw object, simple, from the jQuery object

  • 4

    @Sergio very good :D Ahh, and the last example expresses well why I do not use pure javascript :3

  • I didn’t understand anything. Ended up bringing me more doubts, because I don’t know what some terms mean, as event handler. Do you mind explaining the function of this in a nutshell? If the this simply returns the pure element, it is not the same thing to call such an element by name?

  • @Yoyo the this can be different things in different cases. It depends on a lot of things. If you have questions creates a new question that I am happy to answer. Also look for other questions with answers to learn more.

  • @Yoyo if you don’t understand the answer not to devaluations... you can explain better that part doesn’t make sense?

  • I believe that in the end I need more general knowledge in JS to be able to understand this. I lack basis

20

$() is the jQuery constructor function.

this is a reference to the DOM element invoked.

So, basically, in $(this), you’re just passing by this for the function $() as a parameter, you can call jQuery methods and functions.

Interesting:

  • $(this)[0] === this
  • $("#myDiv")[0] === document.getElementById("myDiv")

18

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.

  • Yeah, the $this certainly can be confusing for the uninitiated. The elephant comparison deserved a <h1>.

  • 1

    @brasofilo hehe I had a math teacher who liked to create "elephant" function parameters so students wouldn’t get addicted to "x" (and she would draw a little elephant in the middle of the formulas, it wasn’t just the word "elephant"... : P)

  • 1

    I also have miss my teacher there in Miraí, how much mischief with Javascript at the time of recreation :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.