const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the <b>person</b> object.</p>
<p>Because <b>fullName</b> is a method of the person object.</p>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>
En JavaScript, la palabra clave this
se refiere a un objeto.
Qué objeto depende de cómo se invoca (usa o llama) este
.
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, este
se refiere al objeto global.
En una función, this
se refiere al objeto global.
En una función, en modo estricto, este
es indefinido
.
En un evento, este
se refiere al elemento que recibió el evento.
Métodos como call()
, apply()
y bind()
puede referir este
a cualquier objeto.
este
no es una variable. Es una palabra clave. No puede cambiar el valor de this
.
Cuando se usa en un método de objeto, este
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.
fullName : function() {
return this.firstName + " " + this.lastName;
}
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the <b>person</b> object.</p>
<p>Because <b>fullName</b> is a method of the person object.</p>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>
Cuando se usa solo, este
se refiere al objeto global.
Porque este
se ejecuta en el ámbito global.
En una ventana del navegador, el objeto global es [object Window]
:
let x = this;
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the window object:</p>
<p id="demo"></p>
<script>
let x = this;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
En el modo estricto, cuando se usa solo, este
también se refiere al objeto global:
"use strict";
let x = this;
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the window object:</p>
<p id="demo"></p>
<script>
"use strict";
let x = this;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
En una función, el objeto global es el enlace predeterminado para este
.
En una ventana del navegador, el objeto global es [object Window]
:
function myFunction() {
return this;
}
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the the window object:</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = myFunction();
function myFunction() {
return this;
}
</script>
</body>
</html>
El modo estricto de JavaScript no permite el enlace predeterminado.
Entonces, cuando se usa en una función, en modo estricto, this
es indefinido
.
"use strict";
function myFunction() {
return this;
}
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In a function, by default, <b>this</b> refers to the global object.</p>
<p>Strict mode does not allow default binding, so <b>this</b> is:</p>
<p id="demo"></p>
<script>
"use strict";
document.getElementById("demo").innerHTML = myFunction();
function myFunction() {
return this;
}
</script>
</body>
</html>
En los controladores de eventos HTML, this
se refiere al elemento HTML que recibió el evento:
<button onclick="this.style.display='none'">
Click to
Remove Me!
</button>
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<button onclick="this.style.display='none'">Click to Remove Me!</button>
</body>
</html>
En estos ejemplos, este
es el objeto persona:
const person = {
firstName : "John",
lastName : "Doe",
id : 5566,
myFunction : function() {
return this;
}
};
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the <b>person object</b>.</p>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName : "John",
lastName : "Doe",
id : 5566,
myFunction : function() {
return this;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML = person.myFunction();
</script>
</body>
</html>
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " +
this.lastName;
}
};
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example, <b>this</b> refers to the <b>person</b> object.</p>
<p>Because <b>fullName</b> is a method of the person object.</p>
<p id="demo"></p>
<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>
</body>
</html>
es decir, this.firstName es la propiedad firstName de this (el objeto persona).
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.
El método de llamada de función()
El método de aplicación de función()
El método de función bind()
El siguiente ejemplo llama a persona1.fullName con persona2 como argumento, esto se refiere a persona2, incluso si nombre completo es un método de persona1:
const person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person2 = {
firstName:"John",
lastName: "Doe",
}
// Return "John Doe":
person1.fullName.call(person2);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>The JavaScript <i>this</i> Keyword</h1>
<p>In this example <strong>this</strong> refers to person2, even if it is a method of person1:</p>
<p id="demo"></p>
<script>
const person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person2 = {
firstName:"John",
lastName: "Doe",
}
let x = person1.fullName.call(person2);
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
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:
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);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Function bind()</h1>
<p>This example creates 2 objects (person and member).</p>
<p>The member object borrows the fullname method from person:</p>
<p id="demo"></p>
<script>
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);
document.getElementById("demo").innerHTML = fullName();
</script>
</body>
</html>
Para determinar a qué objeto este
se refiere; utilice la siguiente precedencia de orden.
Objeto
unir()
aplicar() y llamar()
Método de objeto
Alcance global
¿Se llama this
en una función usando bind()?
¿Está esto
en una función que se llama usando apply()?
¿Se llama this
en una función mediante call()?
¿Está esto
en una función de objeto (método)? <p>¿Está esto
en una función en el ámbito global?