Created
December 6, 2012 18:48
-
-
Save shazow/4227021 to your computer and use it in GitHub Desktop.
Closure scopes in JavaScript.
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
(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 defaults to the root scope (in browsers, that's `window`). | |
(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 | |
var myscope = {}; | |
(function () { | |
this === myscope; | |
(function () { | |
this === myscope; | |
(function() { | |
// There is no fn.call(...), so we get an unspecified scope | |
// Note that scope does not get inherited from the parent closure. | |
this === window; | |
})(); | |
}).call(this); | |
}).call(myscope); | |
// Similar functionality can be achieved by binding scope to a variable. | |
(function () { | |
// `this` #1 | |
var foo = this; | |
var bar = 42; | |
(function () { | |
bar === 42; | |
// `this` #2, but you can still use `foo` and `bar` 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 () { | |
this === window; | |
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