33
loading...
This website collects cookies to deliver better user experience
// this en el scope global
console.log(`this: ${this}`);
// Print: this: [object Window]
function whoIsThis() {
return this
}
console.log(`whoIsThis: ${whoIsThis()}`);
// Print: whoIsThis: [object Window]
Al llamar la función directamente JavaScript le asigna Window.
function whoIsThisStrict() {
'use strict'
return this
}
console.log(`whoIsThisStrict: ${whoIsThis()}`)
// Print: whoIsThisStrict: undefined
Strict mode nos sirve para evitar algunos errores
Se refiere a un objeto. Ese objeto es el que actualmente está ejecutando un pedazo de código.
// this en el contexto de un objeto
const person = {
name: 'Gabriel',
saludar: function() {
console.log(`Hola soy ${this.name}`);
},
};
person.saludar();
// Print: Hola soy Gabriel
// this cuando sacamos a una función de un objecto
const person = {
name: 'Gabriel',
saludar: function() {
console.log(`Hola soy ${this.name}`);
},
};
// Pasamos la función como referencia
const accion = person.saludar;
accion();
// Print: Hola soy
accion()
, no se está llamando dentro del contexto de un objecto.This en este caso sería Window
// this en el contexto de una "clase"
function Person(name) {
this.name = name;
}
Person.prototype.saludar = function() {
console.log(`Me llamo ${this.name}`);
}
const angela = new Person('Angela');
angela.saludar();
// Me llamo Angela