3 ms·
I just don’t get the class/prototype approach, honestly. It really seems to me that you get almost all of the benefits and more by just returning an object from
by wwright 7y ago
I just don’t get the class/prototype approach, honestly. It really seems to me that you get almost all of the benefits and more by just returning an object from a closure, which has the extra benefits of encapsulation and using only simple language features that a JS user pretty much has to use at some point:
const createCounter = ({ startAt = 0, incremementBy = 1 }) => {
let count = startAt
return {
currentCount: () => count,
step: () => {
count += incremementBy
}
}
}
const counter = createCounter({ startAt: 5 })
counter.step()
versus
class Counter {
constructor({ startAt = 0, incrementBy = 1 }) {
this.startAt = startAt
this.incrementBy = incrementBy
this.count = 0
}
step() {
this.count += this.incrementBy
}
}
const counter = new Counter({ startAt: 5 })
- gatherhunterer 7y agoJavaScript classes are pure syntactic sugar for object constructor functions. If the syntactic sugar does not make your code cleaner then don’t use it. Methods with arrow syntax offer implicit function binding and TypeScript adds abstract classes as well as abstract, private, protected and readonly fields. New language features aren’t supposed to replace simple logic that has always worked. They are there to provide new options for programming patterns.