Skip to content

Instantly share code, notes, and snippets.

@dnasca
Created July 29, 2015 05:25
Show Gist options
  • Select an option

  • Save dnasca/a01f496c23fc18d5871f to your computer and use it in GitHub Desktop.

Select an option

Save dnasca/a01f496c23fc18d5871f to your computer and use it in GitHub Desktop.
Scope follows a function. Creating a simple state object.
var createIdempotentWorker = function() {
var isWorking = false;
return {
doWork: function() {
if (isWorking) {
console.log("I'm already working");
return;
}
isWorking = true;
console.log("Starting work");
}
};
};
worker = createIdempotentWorker(); //everytime this function is called, a new local scope is created on line 2
//call #1 - worker.doWork() //output: "Starting work"
//call #2 - worker.doWork() //output: "I'm already working"
callCallback = function (cb) {
cb();
};
// scope gets carried around with the function
callCallback(worker.doWork); //output: "Starting work"
callCallback(worker.doWork); //output: "I'm already working"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment