Created
September 6, 2017 13:25
-
-
Save doug2k1/473d3f33b6a78d05a0938449c78a0c8c to your computer and use it in GitHub Desktop.
'this' no JavaScript: bind - 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' | |
} | |
const enemy = { | |
name: 'Sephirot' | |
} | |
// Função declarada global. | |
// Se chamar direto, o 'this' seria 'global' ou 'window'. | |
const sayName = function () { | |
console.log(this.name) | |
} | |
// Usando 'bind' para criar novas funções que fazem a mesma coisa | |
// da função 'sayName', mas definindo o 'this' manualmente. | |
const sayPlayerName = sayName.bind(player) | |
const sayEnemyName = sayName.bind(enemy) | |
sayPlayerName() // Cloud | |
sayEnemyName() // Sephirot |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment