DEV Community

Cover image for JavaScript: Um pouco sobre o This
Cristian Magalhães
Cristian Magalhães

Posted on • Edited on

1

JavaScript: Um pouco sobre o This

Eae gente bonita, beleza?

Dessa vez venho falar um pouco sobre a palavra-chave this no JavaScript. Ela é comum em diversas linguagens, porém ela pode ser um pouco confusa no JS e aqui vou te explicar o porquê.

Como funciona o this?

Antes de tudo é importante nós entendermos como o this funciona normalmente.

O this é uma palavra-chave para se referir aos membros de uma classe (métodos e propriedades). E é usado em outras linguagens de programação como o Java, por exemplo.

Exemplo de uso do this em java


class Pessoa {
  String nome;
  int idade;
  public Pessoa(String nome, int idade) {
    this.nome = nome;
    this.idade = idade;
  }

  int getIdade() {
    return this.idade;
  }


  String getNome() {
    return this.nome;
  }

  public void falarNome() {
    System.out.println("Meu nome é: "+ this.getNome());
  }

  public void falarNomeEIdade() {
    System.out.println("Meu nome é: "+ this.getNome()+ " e tenho "+ this.idade+ " anos...");
  }
}

class Main {
  public static void main(String[] args) {
    Pessoa p1 = new Pessoa("Cristian", 24);
    p1.falarNome();
    p1.falarNomeEIdade();
  }
}
Enter fullscreen mode Exit fullscreen mode

Nesse exemplo o this é usado para referenciar as propriedades nome e idade e também os métodos falarNome e falarNomeEIdade, ou seja, tudo que está no escopo da classe (guarde isso, ok?).

O problema no JS

No JavaScript temos dois tipos de funções, certo? As declaradas com a palavra-chave function e as arrows function () => {}. É importante você saber aqui que as arrow functions não tem um escopo próprio, então quando você usa o this você acaba pegando as propriedades e métodos do escopo anterior. Então é importante você sempre se atentar nos momentos que você vai usar o this.

Também existe o tema contexto por trás do this no JS, em breve venho aqui e explico para vocês.

Se chegou até aqui, me segue la nas redes vizinhas.

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay