Created
August 26, 2015 18:38
-
-
Save george-hawkins/01aa8274de05c95afd28 to your computer and use it in GitHub Desktop.
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
'use strict'; | |
var globalFoo; | |
function Foo(name) { | |
this.name = name; | |
} | |
function captureGlobalFoo(name) { | |
globalFoo = new Foo(name); | |
return function () { | |
return globalFoo; | |
} | |
} | |
function captureLocalFoo(name) { | |
var localFoo = new Foo(name); | |
return function () { | |
return localFoo; | |
} | |
} | |
var alpha = captureGlobalFoo('alpha'); | |
var beta = captureGlobalFoo('beta'); | |
var gamma = captureLocalFoo('gamma'); | |
var delta = captureLocalFoo('delta'); | |
console.log('alpha', alpha()); | |
console.log(' beta', beta()); | |
console.log('gamma', gamma()); | |
console.log('delta', delta()); | |
// Outputs: | |
// | |
// alpha { name: 'beta' } <-- we've lost Foo('alpha'). | |
// beta { name: 'beta' } | |
// gamma { name: 'gamma' } | |
// delta { name: 'delta' } | |
// | |
// The closure created by captureGlobalFoo(...) captured the mutable globalFoo | |
// and not its particular value at the time the closure was created. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment