Closures and Private Variables in JavaScript
Using closures to implement private in JavaScript.
~/posts/closure-and-private $ cat post.md
“Private” in JavaScript
JS is object-oriented, so an object eventually wants something like
private members. Other languages have first-class support: C++ has
public: and private:, Java has private / protected / friendly.
What’s the JS equivalent?
Why bother
- Better encapsulation, less coupling.
- Free to refactor a class’s internals — outside callers can’t notice.
- Fine-grained control over how members are accessed.
- Hides implementation details.
In practice, for a small self-contained project, private mostly buys you “don’t pollute subclasses” and “keep the public API surface clean.” Once you actually need permission or boundary control, it earns its keep.
How to do it in JS
function Container(param) {
this.member = param;
}
const myContainer = new Container("abc");
myContainer.member is "abc" — a plain constructor pattern; any of
the other object-creation patterns gets you to the same place.
JS variables declared with let / var are scoped. You can lean on
that to keep a member truly private:
function Container(param) {
let member = param;
}
const myContainer = new Container("abc");
But now member is unreachable from outside. So expose an accessor:
function Container(param) {
let member = param;
return () => member;
}
const myContainer = new Container("abc");
Or pin the accessor onto an outer name:
let get = null;
function Container(param) {
let member = param;
get = () => member;
}
const myContainer = new Container("abc");
(In strict mode, declare let get = null; in an outer scope first.)
The mechanic itself is trivial — the more interesting part is articulating why you’d want it.