Skip to content

Instantly share code, notes, and snippets.

@odytrice
Created August 13, 2016 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odytrice/40abd6472a4249abcc4cfb511f633522 to your computer and use it in GitHub Desktop.
Save odytrice/40abd6472a4249abcc4cfb511f633522 to your computer and use it in GitHub Desktop.
This shows the relationship between Objects and Closures
//External state
let z = 5;
//this closure implicitly contains the value of z
let closure = function(x){
return x + z;
}
//The above loosely translates to..
class ObjectClosure{
//private state
z
//The state is "captured" by the object
constructor(state){
this.z = state;
}
//This is the equivalent of invoking the closure
invoke(x){
return x + z
}
}
console.assert(closure(2) === new ObjectClosure(z).invoke(2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment