Skip to content

Instantly share code, notes, and snippets.

@CatTail
Created July 12, 2013 02:22
Show Gist options
  • Save CatTail/5980956 to your computer and use it in GitHub Desktop.
Save CatTail/5980956 to your computer and use it in GitHub Desktop.
Javascript code explain closure by movie inception.
/**
* Platform [email protected] Arch Linux
* Date 2013-07-12 09:43:15
* @author [email protected] (cattail)
*
* @fileoverview Javascript code explain closure by movie inception.
* dream - function
* everything in dream including secret - scope
* people inside dream - executable code
*/
(function () {
var dream = function () {
var experience = Math.random();
console.log(experience);
};
dream();
}());
// extend variable life circle
(function () {
var secret;
var dream = function () {
secret = 'Love X';
console.log(secret);
};
dream();
// another people
console.log(secret);
}());
// privacy
(function () {
var dream = (function () {
var secret;
return function () {
secret = 'Love X';
console.log(secret);
};
}());
dream();
}());
// how to break
(function () {
var thief = {};
var architect = function () {
var buildings = ['bridge', 'river', 'building'];
var projections = {};
// much more
return function dream () {
// people 1
projections.secret = 'Love X';
// thief
thief.steal = function () {
console.log(projections.secret);
};
thief.inception = function (secret) {
projections.secret = secret;
};
};
};
var dream = architect();
dream(); // 'Love X'
thief.steal();
thief.inception('Love Y');
thief.steal();
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment