A Simple Javascript Library Design
When building a JavaScript library, you may find yourself on some code architecture issues. Should I use a constructor function, maybe with a prototype inheritance, isolating in a module or a mix of all of this? A library should have a well-defined public interface and protect itself from a carelessly programmer. In this post, I’m going to build a super simple library to illustrate some code designs.
The library has one purpose: to create Person
objects. A Person
object has a name
, which is assigned in the person constructor and cannot be changed after the person was created. A Person
object also have a me
function that describes the person himself.
Some approaches are presented below as well as their pros and cons.
1 - Constructor function
Cons:
-
the
name
is not a private variable; -
the
me
function is created for each new objectPerson
.
2 - Constructor function and prototype
Pros:
- the
me
function is created only once. Each newPerson
object inherits theme
function through prototype.
Cons:
- the
name
is not a private variable.
3 - Revealing Module Pattern
Pros:
- the
name
is a private variable.
Cons:
- the
me
function is created for each new objectperson
.
4 - A Different Module Flavor
Pros:
- the
me
function is created only once. Each newPerson
object inherits theme
function through prototype.
Cons:
- although the
name
is a private variable, it is shared by allPerson
objects. Therefore, thefoo
person changes thebernardo
person name.
5 - Constructor function, prototype and getter function
Pros:
-
the
name
is a private variable; -
the
me
function is created only once. Each newPerson
object inherits theme
function through prototype.
Cons:
- the
getName
function should not be public because it is used only internally.
6 - Bind to solve
Pros:
-
the
name
is a private variable; -
the
me
function is created only once. Each newPerson
object inherits theme
function through prototype.
Cons:
- None, this is my preferred pattern.
If the return is this way:
It will not work because the this
in the me
function references a anonymous object. You must bind the me
function to right object in the return statement.