How to Define a Private Constructor in JavaScript

Use a private constructor key.

Lincoln W Daniel
ModernNerd Code

--

Somebody asked the below question on StackOverflow. There were a good number of answers, but none of them seem to meet my standards of code: efficient, easy to read, easy to extend, and easy to maintain.

The existing answers included using immediately invoked function expressions (IIFE), object prototype manipulations, proxy objects, class-level global flags to determine when to throw an error during construction, and even error stack string comparisons to enforce the use of a factory function 😭

I truly believe that my answer to the OP’s question is the most sensible, so I’ve shared it below. Fortunately, other engineers agree with my approach, as they’ve voted it to the second top answer; since the top answer was posted in 2014, 8 years ahead of mine, this tells me my approach will eventually move to the top position in due time. If you disagree, I’d love to hear your thoughts in the comments.

My Approach: Use a private constructor key

In order to create a private constructor in JS, I like to create a private key that is only accessible in the class (function) file and provide a static factory function as the only allowed way to construct said class:

--

--

Lincoln W Daniel
ModernNerd Code

Chief Bull @ BullAcademy.org ® Elevating writers @ ManyStories.com. Author @JavaForHumans Ex: Editor in Chief MarkGrowth (acq.), Engineer @Medium @GoPuff