DEV Community

Discussion on: React Is Eating Itself

Collapse
 
gsonderby profile image
Gert Sønderby

Actual bugs? Not on my own watch, no. But I have seen juniors with some extremely wrong ideas about how classes work in JS, which hampered them. The class keyword is syntactic sugar, as you know - by itself not a bad thing. However, it obscures things - and it makes people think in ways that cause them problems when easier solutions are available.

Your second example isn't bad - but for proper equivalence the first one would have to look like this:

function foo() {
  this.name = "george";
  this.age = 42;
  this.sayHello = () => console.log("Hello")
}

Then you can new either one and get an instance.

Now what happens when Fred the Junior goes const bar = new foo(); bar.sayHello = () => console.log('Begone'); bar.sayHello();? Probably what he expected. But then Andy the Junior goes delete bar.sayHello(); because he needs that to not be present, and... Well, that didn't go to plan.

Consider this instead:

const foo = () => ({
  name: "george";
  age: 42;
  sayHello: () => console.log("Hello")
});

A simple factory function, same outcome as your top example except you can get more of them. Results are a lot easier to reason about, what you see is what you get, there's no secret machinery in the engine.

I'm just not aware of any advantage of classes in JS that makes them, their pitfalls, and the wrong ideas they spawn, worth it.

Meanwhile, my last two years were spent building exactly the kinds of abstractions you speak of, and as I mentioned, no classes in there. None needed.