Skip to content

Instantly share code, notes, and snippets.

@jkbrzt
Forked from shazow/gist:4227021
Created December 6, 2012 19:44
Show Gist options
  • Save jkbrzt/4227667 to your computer and use it in GitHub Desktop.
Save jkbrzt/4227667 to your computer and use it in GitHub Desktop.
Closure scopes in JavaScript.
(function() {
// This is a new closure. If things that happen here don't have side-effects on outside scope,
// then whatever happens here will not be visible outside of it.
(function() {
// You can make closures inside of closure (inside of closures). Wee.
})();
})();
// Unspecified scope
(function () {
// `this` == window
(function () {
// `this` == window
(function() {
// `this` == window
})();
})();
})();
// Specifying scope using fn.call(...)
// See: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call
(function () {
// `this` #1
(function () {
// `this` #1
(function() {
// `this` #1
}).call(this);
}).call(this);
})();
// Similar functionality can be achieved by binding scope to a variable.
(function () {
// `this` #1
var foo = this;
(function () {
// `this` #2, but you can still use `foo` from the previous scope.
// You could even do `this = foo` if you're willing to live with yourself after doing that.
});
})();
// More arbitrary scope
(function () {
var foo = {'bar': 42};
(function () {
this === foo;
}).call(foo);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment