Skip to content

Instantly share code, notes, and snippets.

@matey-jack
Created January 16, 2018 10:01
Show Gist options
  • Save matey-jack/95877a6759cce971fddb4197bb645302 to your computer and use it in GitHub Desktop.
Save matey-jack/95877a6759cce971fddb4197bb645302 to your computer and use it in GitHub Desktop.
Closures manipulate variables directly (but they have to be spelled right!)
'use strict';
function scope() {
var i = 0;
var s = "original";
var b = true;
var o = { field: 0 };
return {
inc: function () { i++; },
reset: function () { i = 42; },
get: () => i,
// had a lot of trouble when my string var was called 'princess' and the function assigned to 'princes'.
// that's why we absolutely always need 'use strict'!
resetString: function () { s = "changed"; },
getString: () => s,
resetBool: function () { b = false; },
getBool: () => b,
resetObject: function () { o = { noField: 0 }; },
getObject: () => o,
}
}
function main() {
const blackbox = scope();
console.log("numbers and booleans are passed as variables");
console.log(blackbox.get());
blackbox.inc();
console.log(blackbox.get());
blackbox.reset();
console.log(blackbox.get());
console.log(blackbox.getBool());
blackbox.resetBool();
console.log(blackbox.getBool());
console.log("(references to) strings and objects are also passed as variables");
console.log(blackbox.getString());
blackbox.resetString();
console.log(blackbox.getString());
console.log(blackbox.getObject());
blackbox.resetObject();
console.log(blackbox.getObject());
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment