/**
* This sozinho objeto pai (console do node ou navegador)
*/
console.log(this);
/**
* This como objeto global de uma função
*/
(function () {
console.log(this);
})();
/**
* This utilizado em método de um objeto
*/
const pessoa = {
firstName: 'André',
lastName: 'Soares',
id: 1,
fullName: function () {
return this.firstName + ' ' + this.lastName;
},
getId: function () {
return this.id;
},
};
console.log(pessoa.fullName());
console.log(pessoa.getId());
/**
* This utilizado em um evento
*/
document.getElementById('btn').addEventListener('click', function () {
console.log(this);
});
/**
* Usando call para fazer referencia a um elemento
*/
const novaPessoa = {
nome: 'Miguel',
};
const animal = {
nome: 'Murphy',
};
function getSomething() {
console.log(this.nome);
}
getSomething.call(novaPessoa);
getSomething.call(animal);
const myObj = {
num1: 2,
num2: 4,
};
function soma(a = 0, b = 0) {
console.log(this.num1 + this.num2 + a + b);
}
soma.call(myObj);
soma.call(myObj, 2, 2);
/**
* Usando apply para fazer referencia a um elemento
*/
getSomething.apply(novaPessoa);
getSomething.apply(animal);
soma.apply(myObj, [4, 5]);
/**
* Usando bind para clonar a referencia a um elemento
*/
const retornaNomes = function () {
return this.nome;
};
let bruno = retornaNomes.bind({ nome: 'Bruno' });
console.log(bruno());