Peter Seliger
2 min readJan 17, 2024

--

Already with the first given example code, the difference in between two objects, each created with its unique Parser (constructor vs factory function) is much bigger than what the author tries to nonchalantly put aside with … "The following two snippets are identical in spirit." And that "... the class parser requires the new keyword while the const parser does not" ... is by far not ... "[t]he only difference".

The biggest is the closure based total protection of the factory object's language variable which only can be accessed (non writable) via the object’s sole owned getLanguage method, whereas a Parser instance features a writable public own language property, thus rendering the additionally implemented prototypal getLanguage method actually useless.

The true class based counterpart of the Parser factory has to look like this ...

class Parser {
#language;

constructor(language) {
this.#language = language;
}
getLanguage() {
return this.#language;
}
}

… but of cause there are still differences within the created objects besides their types. An instance of the above implemented Parser type does need to borrow its getLanguage method because it does not own it itself, but any factory object does own it.

Since I myself ’am a friend of factory functions, privacy by closures and object composition, I have to stress that an article which tries to convince the audience of why and how to follow pattern A in favor over pattern B, has to come up with precise use cases, thoroughly picked examples and perfectly implemented code in order to stay credible from the beginning to the very end, especially when ragging on B.

Here we have a false start and it does not get better with the second example code which gives it a try comparing subclassing with techniques where one derives new object features from base objects.

--

--

No responses yet