5

Yes there are many ways to create and use objects. So why/when is it better to create a constructor versus declare a class and use the constructor() method? My instructor said it doesn't make a difference but I don't believe him.

// 1
function Grumpy(name, profile, power){
    this.name = name;
    this.profile = profile;
    this.power = power;
}

Versus

// 2
class Grumpy{
    constructor(name, profile, power){
        this.name = name;
        this.profile = profile;
        this.power = power;
    }
}
Katherine R
  • 1,107
  • 10
  • 20
  • 1
    The class syntax is just syntax sugar. Inside the javascript engine, the class gets turned into the constructor syntax. So your instructor is right. So deciding between the two is more a case of preference, what your team uses and what browsers you have to support. – Shilly Dec 14 '17 at 12:21
  • Or maybe dup of https://stackoverflow.com/questions/36099721/javascript-what-is-the-difference-between-function-and-class – Mehdi Benmoha Dec 14 '17 at 12:23
  • 1
    A good reason, imho, is that javascript classes usually offer better intellisense experience than Constructors when used in several code editors. – Sergeon Dec 14 '17 at 12:26
  • 1
    Many JS enhancements or JS languages that "extend" JS are syntactical sugar. It doesn't mean that it makes no difference in practice to use one or the other. The answer in the duplicate addresses the question. – davidxxx Dec 14 '17 at 12:30

1 Answers1

8

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.

For more defailts, see MDN

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
zabusa
  • 2,520
  • 21
  • 25