Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
'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