Why Classes are better than Closures

Ben Lugavere
3 min readNov 21, 2018

Classes in JavaScript received a ton of flak by the javascript community when they first came out, but for no good reason. They provide syntactical sugar around javascript’s prototypal inheritance features which are one of the most powerful aspects of language. They introduced no new functionality, but made more obscure parts of the language more explicit and approachable for those coming from other languages. I’m referring of course, to this and the new keyword.

function MyFunc () {}
const instance1 = MyFunc();
const instance2 = new MyFunc();
instance1 === instance2 // false

Execution context in javascript is everything, and this makes object oriented programming a bit tricky. Functions in javascript are first class citizens and can be used outside of the context of the class or instance they’re defined in.

const cat = {
name: 'foofoo',
speak(){
console.log(this.name);
}
}
const { speak } = cat;cat.speak(); // foofoo
speak(); // undefined

Arrow functions were recently introduced as well where the this argument is bound to the enclosing scope.

class Cat {
constructor() {
this.name = 'foofoo';
this.speak = () => console.log(this.name);
}
}

--

--