JavaScript Closures
by horhey
JavaScript
// closures
// 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 + '"'
];
// 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( jd) {
//return adventures.pop();
return adventures[jd];
}
};
};
// 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(0));
window.console.log(littleGirl.story(2));
//window.console.log(littleGirl.story());
// a more technical example:
var db = (function() {
// "private"
var data = {};
// getter/setter
return function(key, val) {
return val === undefined ? data[key] : data[key] = val;
};
})();
window.console.log("db('foo'): ", db('foo'));
window.console.log("db('foo', 'bar'): ", db('foo', 'bar'));
window.console.log("db('foo'): ", db('foo'));
window.console.log("db: ", db);