-
-
Save jkbrzt/4227667 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 | |
(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