Last active
May 30, 2016 00:41
-
-
Save jeserodz/99f1bd67efc9f7ec3f45abcbb2dcc2e5 to your computer and use it in GitHub Desktop.
JavaScript Examples: 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
var closure1; | |
var closure2; | |
var buildFullName = function(fname, lname) { | |
// building full name inside the execution context | |
var fullName = fname + ' ' + lname; | |
// defining a function to return fullname according to execution context | |
var printFullName = function() { | |
return fullName; | |
}; | |
// returning the fuction object | |
return printFullName; | |
}; | |
// Each time a function is invoked, a new execution context is created and persisted | |
// in memory. As buildFullName() returns a function that uses its context variables, | |
// then assigning the returned function to an outer context variable will use the values in | |
// the especific context when the function was invoked | |
var closure1 = buildFullName('jese', 'rodriguez'); | |
var closure2 = buildFullName('charolyn', 'mendoza'); | |
console.log('Closure 1 = ' + closure1()); | |
console.log('Closure 2 = ' + closure2()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment