DEV Community

Discussion on: Do you need classes in JS/TS?

 
peerreynders profile image
peerreynders • Edited

Prototype-based programming is all but gone, save for polyfills.

class keyword or not - the objects instantiated still rely on prototypal inheritance. And in performance conscious code bases constructor functions are still "assembled" - that way method implementations can be shared by otherwise unrelated constructor functions (see Preact).

class vs prototype

Class free OOP doesn't relate to implementing inheritance with prototypes. "OOP with functions" typically refers to a plain literal object holding references to functions that share data through the closure of the factory function that created them.

function createDog(name) {
  let hungry = false;
  return {
    get type() {
      return 'dog';
    },
    get name() {
      return name;
    },
    set name(n) {
      name = n;
    },
    get isHungry() {
      return hungry;
    },
    play() {
      hungry = true;
    },
    feed() {
      hungry = false;
    },
    makeSound() {
      alert(hungry ? 'groan....' : 'Woof woof.');
    },
  };
}
Enter fullscreen mode Exit fullscreen mode

OOP with functions in JavaScript
How to decide between classes v. closures in JavaScript.

classes in JS are still the better way to do OOP.

Keeping in mind that in JavaScript Classes are a template for creating objects - for the most part they are just a creational convenience (until more is needed) but they are not the only way to create objects in JavaScript; unlike in mainstream class-based object-oriented languages.

James Coplien
"How many of you do object-oriented programming? What language? Java is the only language in which you cannot do object-oriented programming. Huh? Other languages. Smalltalk - no. C# - no. Python - no. No. Any JavaScript programmers here? Here are my object-oriented programmers - they're writing objects - the rest of you are writing classes. "

it's about polymorphism

JavaScript has always achieved polymorphism through "duck typing" - no classes required. TypeScript's structural typing is an expression of that. Either a value satisfies an interface or type alias or it does not - no need to implement, inheritor extend anything.

clear class structure

More often than not I hear people complaining about brittle, deep, complex class hierarchies.

"Favor object composition over class inheritance"
Gamma, Erich et al. "Design Patterns Elements of Reusable Object-Oriented Software". Putting Resuse Mechanisms to Work, p.20, 1994

So a "clear class structure" doesn't seem to be a pit of success for OOD/P in practice.

Functional programming is certainly seeing a new renaissance in JS.

I think that is a red herring. I myself have described JavaScript as function-oriented but using an FP-flavoured expression-based (as opposed to statement-based) style leads more to value-oriented programming.