JSFiddle - React, Tailwind, and code Playground
JavaScript
// No closures!
// Nothing is referenced inside this function (or its interal code) that isn't already available in scope, so closures are avoided.
var buildCachedSumDataFunctionWithoutClosure = function(initialValue) {
var specialFunction = function secretName(newValue) {
// The value supplied initially is used via the named function internally
return secretName.cached + newValue;
};
specialFunction.cached = initialValue;
return specialFunction;
};
var cachedWith5 = buildCachedSumDataFunctionWithoutClosure(5);
console.log(cachedWith5(10)); // 15
var cachedWith2 = buildCachedSumDataFunctionWithoutClosure(2);
// You can make as many as you need
console.log(cachedWith2(2)); // 4
// Data is not shared across calls to buildCachedSumDataFunctionWithoutClosure
console.log(cachedWith5(4)); // 9
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Even if the scope would otherwise allow access, this function object form creates an "internal reference name" for itself
var test = function that(newValue) {
return that.cached + newValue;
};
test.cached = 6;
try {
console.log(that(4)); // ReferenceError
} catch (e) {
console.log('The `that` reference can only be used internally to that particular function.');
}
console.log('However, this is not magic or providing real privacy. The values stored on the function object can still be obtained via the public reference:');
console.log(test.cached); // 6
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// You can see that this doesn't cause a closure by comparing it to an equivalent function that uses a closure form in the Chrome DevTools, under Scope
// Uncomment the debugger statements to inspect them in the Sources panel (with DevTools open).
var noClosure = function secretFunctionReference(newValue) {
// debugger;
// Scope:...