Utilize a closure:
let getA;
let getB;
let getC;
function initializeStringFormatter (x) {
let language = x;
getA = function () { return 'A' + language }
getB = function () { return 'B' + language }
getC = function () { return 'C' + language }
}
initializeStringFormatter('enUS');
getA();
Closures have the ability to offer the same functionalities as object properties in OOP. There exists a direct correspondence between closures and objects where closures employ scope for attaching variables to functions while objects use bindings for attaching variables to methods.
It is common practice to blend OOP with FP. Even Lisp incorporates an OOP library. A typical JavaScript convention involves returning an object instead of using function names as global variables:
function initializeStringFormatter (language) {
function a () { return 'A' + language }
function b () { return 'B' + language }
function c () { return 'C' + language }
return {
getA: a,
getB: b,
getC: c
}
}
let stringManager = initializeStringFormatter('enUS');
stringManager.getA();
In JavaScript, it is frequent to witness FP developers employing objects primarily as namespaces for functions. State management can be entirely accomplished through closures without relying on object properties.
Note: In FP, languages like Lisp do not necessarily require built-in OOP support; rather, OOP is considered a design pattern or library - the standard OOP library in Lisp being CLOS: the Common Lisp Object System
The drawback of closures is that they are essentially private due to the fact that they are local variables within functions. However, this adheres to good practices seen in the OOP realm where public access to variables should be restricted. By utilizing closures, variable access is exclusively done through functions, akin to the getter/setter design pattern commonly observed in OOP implementations.
Although not completely pure FP, JavaScript still permits the modification of enclosed variables. Nevertheless, the aforementioned function adheres to pure FP standards since the locale
variable remains unmodifiable.
To achieve 100% pure FP in JavaScript, one straightforward approach is to eliminate all instances of let
and var
in code and strictly use const
. While initially feeling unusual, writing programs solely with const
and constant function arguments is feasible. Languages such as JavaScript and Go provide flexibility enabling the use of variables for managing state-based logic seamlessly.