Jersson G Arrivasplata Rojas
TipLenguajesTypeScript1 min de lectura

La palabra clave this

Contexto, bind y arrow functions

this hace referencia al objeto actual. Dentro de un método se refiere al objeto que llama a la función, y su valor puede cambiar según el contexto.

typescript
class Persona {
  nombre: string;
  edad: number;

  constructor(nombre: string, edad: number) {
    this.nombre = nombre;
    this.edad = edad;
  }

  saludar() {
    console.log(`Hola soy ${this.nombre} y mi edad es ${this.edad}.`);
  }

  getEdad() {
    console.log(`Tengo ${this.edad} años.`);
  }
}

let miPersona = new Persona("Juan", 25);
miPersona.saludar(); // Hola soy Juan y mi edad es 25.

Si getEdad() se ejecuta como función independiente, el contexto de this se pierde. bind() fija el valor de this.

typescript
let persona1 = new Persona("Juan", 25);
const obtenerEdad = persona1.getEdad;
obtenerEdad(); // "Tengo undefined años." o un error

let getEdad = persona1.getEdad.bind(persona1);
getEdad(); // Tengo 25 años.

Las arrow functions conservan el this del contexto donde fueron creadas, útil en callbacks o en métodos pasados como argumentos.

typescript
class Coche {
  marca: string;
  constructor(marca: string) {
    this.marca = marca;
  }
  arrancar() {
    console.log(`${this.marca} está arrancando.`);
  }
  parar = () => {
    console.log(`${this.marca} se ha parado.`);
  };
}

let coche1 = new Coche("Ford");
let parado = coche1.parar;
parado(); // Ford se ha parado.
Jersson G. Arrivasplata RojasSoftware Engineer & Technical Leader · Lima, Perú
TipLanguagesTypeScript1 min read

The this keyword

Context, bind and arrow functions

this refers to the current object. Inside a method it refers to the object calling the function, and its value can change with the context.

typescript
class Persona {
  nombre: string;
  edad: number;

  constructor(nombre: string, edad: number) {
    this.nombre = nombre;
    this.edad = edad;
  }

  saludar() {
    console.log(`Hola soy ${this.nombre} y mi edad es ${this.edad}.`);
  }

  getEdad() {
    console.log(`Tengo ${this.edad} años.`);
  }
}

let miPersona = new Persona("Juan", 25);
miPersona.saludar(); // Hola soy Juan y mi edad es 25.

If getEdad() runs as a standalone function, the this context is lost. bind() fixes the value of this.

typescript
let persona1 = new Persona("Juan", 25);
const obtenerEdad = persona1.getEdad;
obtenerEdad(); // "Tengo undefined años." o un error

let getEdad = persona1.getEdad.bind(persona1);
getEdad(); // Tengo 25 años.

Arrow functions keep the this of the context where they were created, which is useful in callbacks or in methods passed as arguments.

typescript
class Coche {
  marca: string;
  constructor(marca: string) {
    this.marca = marca;
  }
  arrancar() {
    console.log(`${this.marca} está arrancando.`);
  }
  parar = () => {
    console.log(`${this.marca} se ha parado.`);
  };
}

let coche1 = new Coche("Ford");
let parado = coche1.parar;
parado(); // Ford se ha parado.
Original post
Jersson G. Arrivasplata RojasSoftware Engineer & Technical Leader · Lima, Perú
TipLinguagensTypeScript1 min de leitura

A palavra-chave this

Contexto, bind e arrow functions

this faz referência ao objeto atual. Dentro de um método, refere-se ao objeto que chama a função, e seu valor pode mudar conforme o contexto.

typescript
class Persona {
  nombre: string;
  edad: number;

  constructor(nombre: string, edad: number) {
    this.nombre = nombre;
    this.edad = edad;
  }

  saludar() {
    console.log(`Hola soy ${this.nombre} y mi edad es ${this.edad}.`);
  }

  getEdad() {
    console.log(`Tengo ${this.edad} años.`);
  }
}

let miPersona = new Persona("Juan", 25);
miPersona.saludar(); // Hola soy Juan y mi edad es 25.

Se getEdad() for executada como função independente, o contexto de this se perde. bind() fixa o valor de this.

typescript
let persona1 = new Persona("Juan", 25);
const obtenerEdad = persona1.getEdad;
obtenerEdad(); // "Tengo undefined años." o un error

let getEdad = persona1.getEdad.bind(persona1);
getEdad(); // Tengo 25 años.

As arrow functions mantêm o this do contexto onde foram criadas, o que é útil em callbacks ou em métodos passados como argumentos.

typescript
class Coche {
  marca: string;
  constructor(marca: string) {
    this.marca = marca;
  }
  arrancar() {
    console.log(`${this.marca} está arrancando.`);
  }
  parar = () => {
    console.log(`${this.marca} se ha parado.`);
  };
}

let coche1 = new Coche("Ford");
let parado = coche1.parar;
parado(); // Ford se ha parado.
Jersson G. Arrivasplata RojasSoftware Engineer & Technical Leader · Lima, Perú

Apoya mis proyectos

Si una librería, guía o recurso de este sitio te fue útil, puedes aportar con Yape o Plin. Ayuda a mantener el código abierto y la documentación.

987 347 691Jersson G. Arrivasplata Rojas · Soles