Skip to content

Instantly share code, notes, and snippets.

@doug2k1
Created September 6, 2017 13:29
Show Gist options
  • Save doug2k1/5b2794a0eb367fc6f50e1b51da30b2f8 to your computer and use it in GitHub Desktop.
Save doug2k1/5b2794a0eb367fc6f50e1b51da30b2f8 to your computer and use it in GitHub Desktop.
'this' no JavaScript: call e apply - https://blog.dmatoso.com/javascript-this-71dd763aad52
const player = {
name: 'Cloud',
hp: 100,
mp: 0,
printStatus () {
console.log(`${this.name} tem ${this.hp} de HP e ${this.mp} de MP.`)
}
}
// Função usa 'this', mas vamos setá-lo no momento da chamada.
const addHPMPToPlayer = function (hp, mp) {
this.hp += hp
this.mp += mp
this.printStatus()
}
player.printStatus() // Cloud tem 100 de HP e 0 de MP.
// Setando o 'this' manualmente usando 'call'
addHPMPToPlayer.call(player, 50, 20) // Cloud tem 150 de HP e 20 de MP.
// Setando o 'this' manualmente usando 'apply'
// (a única diferença é a forma como passamos os demais argumentos)
addHPMPToPlayer.apply(player, [50, 20]) // Cloud tem 200 de HP e 40 de MP.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment