Created
September 6, 2017 13:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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