# The JavaScript this Keyword

---

> En JavaScript, la palabra clave `this` siempre se refiere a un objeto.

---

**Ejemplo:**

```jsx
const person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
```

[**Ver ejemplo**](https://www.w3schools.com/js/tryit.asp?filename=tryjs_this_method)

---

## ¿Qué es **this?**

En JavaScript, palabra clave `this` se refiere a un **objeto**.

**Qué** objeto depende de cómo `this` invoca (usado o llamado).

La palabra clave `this` se refiere a diferentes objetos dependiendo de cómo se use:

| En un método de objeto, this se refiere al objeto. |
| --- |
| Por sí solo, `this` se refiere al objeto global. |
| En una función, `this` se refiere al objeto global. |
| En una función, en modo estricto, `this` es `undefined`. |
| En un evento, `this` se refiere al elemento que recibió el evento. |
| Métodos como `call()`, `apply()` y `bind()` pueden referir this a cualquier objeto. |

---

### Nota

> `this` no es una variable. Es una palabra clave. No puedes cambiar el valor de `this`.

---

## **this en un método**

Cuando se usa en un método de objeto, `this` se refiere al **objeto**.

En el ejemplo de la parte superior de esta página, `this` se refiere al objeto **persona**.

Porque el método `fullName` es un método del objeto **persona**.

**Ejemplo:**

```jsx
fullName : function() {
  return this.firstName + " " + this.lastName;
}
```

[**Ver ejemplo**](https://www.w3schools.com/js/tryit.asp?filename=tryjs_this_method)

---

## this solo

Cuando se usa solo, `this` se refiere al **objeto global**.

Porque `this` se está ejecutando en el ámbito global.

En una ventana del navegador, el objeto global es `[object Window]`:

**Ejemplo:**

```jsx
let x = this;
```

[**Ver ejemplo**](https://www.w3schools.com/js/tryit.asp?filename=tryjs_this)

En **modo estricto**, cuando se usa solo, `this` también se refiere al **objeto global**:

**Ejemplo:**

```jsx
"use strict";
let x = this;
```

[**Ver ejemplo**](https://www.w3schools.com/js/tryit.asp?filename=tryjs_this_alone)

---

## **this** en una función (Predeterminado)

En una función, el **objeto global** es el enlace predeterminado para `this`.

En una ventana del navegador, el objeto global es `[object Window]`:

**Ejemplo:**

```jsx
function myFunction() {
  return this;
}
```

[**Ver ejemplo**](https://www.w3schools.com/js/tryit.asp?filename=tryjs_this_function)

---

## this en una función (Estricto)

El **modo estricto** de JavaScript no permite el enlace predeterminado.

Entonces, cuando se usa en una función, en modo estricto, `this` es `undefined`.

**Ejemplo:**

```jsx
"use strict";
function myFunction() {
  return this;
}
```

[**Ver ejemplo**](https://www.w3schools.com/js/tryit.asp?filename=tryjs_this_strict)

---

## this en controladores de eventos

En los controladores de eventos HTML, `this` se refiere al elemento HTML que recibió el evento:

**Ejemplo:**

```xml
<button onclick="this.style.display='none'">
  Click to Remove Me!
</button>
```

[**Ver ejemplo**](https://www.w3schools.com/js/tryit.asp?filename=tryjs_this_event)

---

## Enlace de método de objeto

En estos ejemplos, `this` es el **objeto persona:**

**Ejemplo:**

```jsx
const person = {
  firstName  : "John",
  lastName   : "Doe",
  id         : 5566,
  myFunction : function() {
    return this;
  }
};
```

[**Ver ejemplo**](https://www.w3schools.com/js/tryit.asp?filename=tryjs_this_object)

**Ejemplo:**

```jsx
const person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
```

[**Ver ejemplo**](https://www.w3schools.com/js/tryit.asp?filename=tryjs_this_method)

Es decir, `this.firstName` es la propiedad `firstName` de `this` (el objeto persona).

---

## Enlace de función explícita

Los métodos `call()` y `apply()` son métodos JavaScript predefinidos.

Ambos pueden usarse para llamar a un método de objeto con otro objeto como argumento.

---

### Veáse también:

[The Function call() Method](https://www.w3schools.com/js/js_function_call.asp)

[The Function apply() Method](https://www.w3schools.com/js/js_function_apply.asp)

[The Function bind() Method](https://www.w3schools.com/js/js_function_bind.asp)

El siguiente ejemplo llama a `person1.fullName` con `person2` como argumento, `this` se refiere a , incluso si `fullName` es un método de `person1`:

**Ejemplo:**

```jsx
const person1 = {
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}

const person2 = {
  firstName:"John",
  lastName: "Doe",
}

// Return "John Doe":
person1.fullName.call(person2);
```

[**Ver ejemplo**](https://www.w3schools.com/js/tryit.asp?filename=tryjs_this_call)

---

## Préstamo de funciones

Con el método `bind()`, un objeto puede tomar prestado un método de otro objeto.

Este ejemplo crea 2 objetos (persona y miembro).

El objeto miembro toma prestado el método de nombre completo del objeto persona:

**Ejemplo:**

```jsx
const person = {
  firstName:"John",
  lastName: "Doe",
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
}

const member = {
  firstName:"Hege",
  lastName: "Nilsen",
}

let fullName = person.fullName.bind(member);
```

[**Ver ejemplo**](https://www.w3schools.com/js/tryit.asp?filename=tryjs_function_bind_borrow)

---

## This precedencia

Para determinar a qué objeto se refiere `this`; utilice la siguiente precedencia de orden.

| Precedencia | Objeto |
| --- | --- |
| 1 | `bind()` |
| 2 | `apply()` y `call()` |
| 3 | Método de objeto |
| 4 | Alcance global |

¿Está `this` en una función que se llama usando `bind()`?

¿Está `this` en una función que se llama usando `apply()`?

¿Está `this` en una función que se llama usando `call()`?

¿Está `this` en una función de objeto (método)?

¿Está `this` en una función en el ámbito global?

---

***W3Schools*** *es el sitio de desarrolladores web más grande del mundo.*
