Created
April 23, 2015 16:44
-
-
Save kylehill/70ef0be5e643c9cdf21b to your computer and use it in GitHub Desktop.
Closures
This file contains hidden or 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
/* | |
A "closure" is created whenever | |
- a function is executed and variables are scoped inside of it, either as params or with var | |
- that function returns an executable function, either by itself or as part of an object/array | |
The locally-scoped variables are then "closed over." Like any other variables defined inside of a function, | |
they are not accessible outside of that scope, but in the special case of a closure they are still accessible | |
by the **returned function**. | |
*/ | |
// ------ | |
// This function does not return a function. Variables defined inside of it go away. | |
var simpleFunction = function(str) { | |
var base = "Hello, " | |
return base + str | |
} | |
console.log(simpleFunction("World")) // prints "Hello, World" | |
console.log(base) // this line errors -- `base` is not defined outside of simpleFunction | |
console.log(str) // this line errors -- `str` is not defined outside of simpleFunction | |
// ----- | |
// This function uses a globally-scoped variable, which persists outside of the function's scope. | |
// It does not return a function, so the variables defined inside of it go away. | |
var salutation = "Hi, " | |
var greetingFunction = function(str) { | |
return salutation + str | |
} | |
console.log(greetingFunction("JavaScript")) // prints "Hi, JavaScript" | |
console.log(salutation) // prints "Hi, " -- globally scoped | |
console.log(str) // this line errors -- `str` is not defined outside of greetingFunction | |
// ----- | |
// This function returns a function. Variables defined inside of the parent function are | |
// "closed over," and accessible only by the child function. | |
var closureFunction = function(num) { | |
var multiplier = 2 | |
return function() { | |
return num * multiplier; | |
} | |
} | |
var twoTimes5 = closureFunction(5) | |
var twoTimes10 = closureFunction(10) | |
console.log(twoTimes5()) // prints 10 | |
console.log(twoTimes10()) // prints 20 | |
console.log(num) // this line errors -- "num" is not defined outside of closureFunction | |
console.log(multiplier) // this line errors -- `multiplier` is not defined outside of closureFunction |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment