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

48

I've always used $(this) regardless of the situation and always worked. Rarely have I had to use one of the others and in those times I did for someone's guidance and not for knowing exactly what I had to do.

  • So what's the difference between the 3 kind of this?
  • When should I use one and when should I use another?
  • Does the code performance change in any way?
asked by RodrigoBorth 22.10.2014 в 17:57
source

3 answers

57

Simple version:

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

More elongated version:

  • this when pointing to an element

When we use this inside for example an event handler we are referring to the element raw, simple, original.

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

The $this is used as a simple variable. It is very common to use $this = $(this); which is a way of saving the reference to the jQuery object in scopes where this is another, such 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 jQuery powers!

In order to use jQuery methods on objects, you must pass the object as a parameter of the jQuery $() function. 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 this it 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;
  };

What gives more work to write: P

To remove the original element from within a jQuery object we can use index, ie var divs = $('div'); gives an object similar to an array where divs [0] is the first div, raw. would be the same as this . You can also use .get() to fetch the simple raw object from the jQuery object

    
answered by 22.10.2014 / 18:02
source
20

$() is the constructor function of jQuery.

this is a reference to the DOM element invoked.

So basically, in $(this) , you're simply passing this to the $() function as a parameter, so you can call jQuery methods and functions.

Interesting:

  • $(this)[0] === this
  • $("#myDiv")[0] === document.getElementById("myDiv")
answered by 22.10.2014 в 18:15
19

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.

    
answered by 22.10.2014 в 19:12