Created
October 29, 2013 10:15
-
-
Save gabeno/7212020 to your computer and use it in GitHub Desktop.
A simple way to understand 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
// 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