Skip to content

Instantly share code, notes, and snippets.

@pedrobritto
Created July 16, 2019 19:21
Show Gist options
  • Save pedrobritto/4104bd5d338609cf5b759172f3b85cc8 to your computer and use it in GitHub Desktop.
Save pedrobritto/4104bd5d338609cf5b759172f3b85cc8 to your computer and use it in GitHub Desktop.
// Closure 1
function sum( a ) {
function inner( b ) {
return a + b;
}
// Função inner é retornada e poderá
// ser utilizada dessa forma estranha
return inner;
}
var add5 = sum( 5 );
add5( 15 );
// Closure 2
var Counter = ( function() {
// Variável que existe apenas dentro de Counter
var privateCounter = 0;
// Função que será reutilizada
function changeBy( val ) {
privateCounter += val;
}
/**
* Retorna métodos que conseguem acessar a
* var privateCounter por conta do escopo léxico.
*/
return {
increment: function() {
changeBy( 1 );
},
decrement: function() {
changeBy( -1 );
},
value: function() {
return privateCounter;
}
}
})();
console.log( Counter.value() );
Counter.increment();
Counter.increment();
console.log( Counter.value() );
Counter.decrement();
Counter.decrement();
console.log( Counter.value() );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment