re: Do we really need classes in JavaScript after all? VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Would it be fair to say that this conversation is fairly steeped in front-end web development? How might you spin this conversation when other pre...
 

Would it be fair to say that this conversation is fairly steeped in front-end web development?

I think the examples used are very front-end. But I think that is because that is the larger audience. But I believe these concepts apply equally to node development as well.

Developers that come from other OO languages, reach for classes first due to familiarity with them. But JavaScript classes do not behave like those other languages, so people get easily tripped up.

JavaScript classes have their quirks due to the complexity of having to retain backward compatibility. JavaScript class Inheritance is mocked, but underneath (and hidden), it's still using prototypal inheritance.

And due to these expectations, it's my opinion that's where a lot of frustration comes in.

I am not a fan of JavaScript classes. To use them properly, you should understand how they are making prototypal inheritance. So you need to understand both anyway.

JavaScript's prototypal inheritance is exposed when you run into code like this:

class Bork {
  constructor() {
    this.message = 'Bork!'
  }
  bork() {
    return this.message
  }
}

const bork = new Bork()
const borkBork = bork.bork

bork.bork() //=> "Bork!"
borkBork() //=> Error("Cannot read property 'message' of undefined")

It is commonly found in React with something like this:

render() {
  // potential bug
  return <button onClick={this.handler} />
}

We have so many workarounds because we have an imperfect solution, the JavaScript class.

IMO, JavaScript classes were a mistake and they lead to much unnecessary confusion. They don't provide anything additional or extra and there are better ways of writing code.

This code is a good example of that as you will not run into any of the pitfalls of this.

Cheers!

code of conduct - report abuse