What is the THIS parameter for?

Asked

Viewed 551 times

2

Something I always see in a lot of code around is the parameter this.

Ex:

$(this).funçao-variável...

I’ve been told that the this serves to "reference" something. But, it was not very clear.

Does anyone know what use/what the this?

2 answers

2

This article of the Code explains very well the use of terminology.

Every Javascript function, when executed, generates an association of the object created by the interpreter through this reserved word. The Ecmascript specification calls this Thisbinding, an event that happens every time a Javascript code is executed and a new execution context is established. The value of this is constant and it exists as long as this execution context exists.

Read more on Learn more about the "this" used javascript

I hope I’ve helped.

2


In Jquery, $(this) refers to the element you are currently using.

For example, if you have created a function Blur from Jquery to a given text field, instead of having to reference the field every time you use it, you can simply use $(this) within the context of the element.

$('#field').blur(function(){
    var field_value = $(this).val(); // $(this).val() se refere ao valor de $('#field')
    alert(field_value);
});

I hope now it’s clear.

Browser other questions tagged

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