-1

I take a look at the following code and have a bad feeling that the older version was much simpler to do.

// Pre ES6: 5 lines
function Car (make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
}

// Post ES6: 7 lines
class Car {
  constructor(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
  }
}

They are both objects at the end of the day. So, why should we use the new construct?

Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115
Grateful
  • 9,685
  • 10
  • 45
  • 77
  • 2
    Because the latter is easier to manage if you have anything more than few instance properties. Add some methods and you'd find out that the class syntax is neater. Make `RaceCar extends Car` and its equivalent and you'll find the class syntax has even more benefits – VLAZ Aug 04 '20 at 05:02
  • It's just part of JavaScript's descent into OOP madness... – Dennis Hackethal Aug 04 '20 at 05:04
  • @weltschmerz Haha.. I can see we have some serious fans here. – Grateful Aug 04 '20 at 05:05
  • 4
    Feel free to define a number of methods, then subclass it in an extensible way, override some methods (including the constructor) that then call the base and then see which looks simpler to understand, maintain and extend. A good programming language design is not just about brevity. – jfriend00 Aug 04 '20 at 05:58

1 Answers1

0

You're not using a lot of the features of classes here - neither in the ES5 nor in the ES6 version. Since your objects don't have any methods, it's hardly necessary to write a constructor function that lets them inherit from a common prototype. You can simplify to a factory function:

function makeCar (make, model, year) {
    return {make, model, year};
}

If you were to define some methods, you'd see the benefits of the simplified syntax clearly.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375