JavaScript Closures
by anandhinava
JavaScript
// once upon a time, there was a princess
var Princess = function() {
// who rode around her world on a unicorn, battled dragons, encountered talking animals, and many other fantastical things.
var unicorn = {
name: 'Sparkles'
};
var dragons = [
'A green one with purple wings',
'A mean black one who breathed fire',
'A fluffy white one that looked like a dog'
];
var talkingAnimals = {
squirrel: "Hello!"
};
// and lived in a wonderful world full of adventures
var adventures = [
'My unicorn ' + unicorn.name + ' had a baby!',
'I fought ' + dragons.length + ' dragons!',
'I met a talking squirrel who said "' + talkingAnimals.squirrel + '"'
];
var adventures1 = [
'I fought ' + dragons.pop() + ' dragons!',
'I fought ' + dragons.pop() + ' dragons!',
'I fought ' + dragons.pop() + ' dragons!'
];
// but she would always have to return back to her dull world of chores and grown-ups
return {
// and she would often tell them of her latest amazing adventure as a princess
story: function() {
return adventures.pop();
},
story1 : function() {
return adventures1.pop();
}
};
};
// but all they could see is a little girl
var littleGirl = new Princess();
window.console.log(littleGirl);
// telling stories about magic and fantasy
window.console.log(littleGirl.story());
window.console.log(littleGirl.story());
window.console.log(littleGirl.story());
// a more technical example: IIFE -- Immediately invoked function execution
var db = (function() {
// "private"
var data = {foo:1};
// getter/setter
return function(key, val) {
window.console.log('typeof data is Array: ', typeof data === 'object');
return val === undefined ? data[key] : data[key] = val;
};
})();
window.console.log("db('foo'): ",...