Created
August 13, 2016 17:25
-
-
Save odytrice/40abd6472a4249abcc4cfb511f633522 to your computer and use it in GitHub Desktop.
This shows the relationship between Objects and Closures
This file contains 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
//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