Skip to content

Instantly share code, notes, and snippets.

@gabeno
Created October 29, 2013 10:15
Show Gist options
  • Save gabeno/7212020 to your computer and use it in GitHub Desktop.
Save gabeno/7212020 to your computer and use it in GitHub Desktop.
A simple way to understand closures...
// a simple function to display a greeting
var sayHello = function() {
return alert('Hello there!');
};
sayHello(); // => Hi there!
// ----------------------------------------
// function returns an object, text preset
var sayHello = function() {
var text = 'Hello there!';
return {
speak: function() { return alert(text); }
};
};
var obj = new sayHello;
obj.speak() // => Hi there!
// ----------------------------------------
var sayHello = function() {
var text = 'Hello there!';
return {
beNice: text = "I am nice!",
beGrim: text = "Fuck off!",
speak: function() { return alert(text); }
};
};
// modify function to close over the variable text which can only be set thru setter methods
var obj = new sayHello;
obj.speak(); // => Hi there!
obj.beNice;
obj.speak(); // => I am nice!
obj.beGrim;
obj.speak(); // => Fuck off!
// the variable is only modifiable through the exposed api and therefore the internal state is much controlled.
// the principle behind closures...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment