I've noticed there are two different ways to effectively write a class (or class-like thing) in JavaScript. Using a simple counter class as an example:
A real class (used as new Counter1()
)
class Counter1 {
constructor(count = 0) {
this.count = count;
}
inc() {
this.count++;
}
get() {
return this.count;
}
}
A function returning an object (used as Counter2()
)
function Counter2(count = 0) {
return {
inc() {
count++;
},
get() {
return count;
},
};
}
I have a lot of code that could be written in either one of these styles. Which should I use?
This is my understanding:
Counter1
can be used with instanceof
and inheritance, but is more verbose and doesn't have real private properties (eg count
property is exposed).
Counter2
is more concise and has real private methods/state (just local variables in the function), but can't be used with instanceof
and inheritance. It also creates new copies of the inc
and get
functions for each instance, which may impact performance? I don't know.