0

Say I have a class Animal that I want to define in JavaScript. What are the advantages and disadvantages to declaring it as...

class Animal {
  constructor(type, noise) {
    this.type = type;
    this.noise = noise;
  }

  makeNoise() {
    console.log(this.noise);
  }
}

versus declaring it as...

function Animal(type, noise) {
  this.type = type;
  this.noise = noise;
  
  this.makeNoise = function () {
    console.log(this.noise);
  }
}

The only thing that I notice is different is that the latter example can actually have private members (declared using var, let, or const declarations), but that was all I could really see.

bill 38
  • 1
  • 1
  • 2
    Your class version will actually place `makeNoise` on the prototype, your latter places it on the instance. IOW: if you created lots of instances, your latter one would be less resource friendly. – Keith Nov 03 '22 at 20:06
  • 3
    Classes also have private members. And the constructor of a class can also use local variables. – Sebastian Simon Nov 03 '22 at 20:10
  • + for Keith's answer about prototype/instance bound functions, and have a look at https://stackoverflow.com/questions/52666266/class-vs-function-constructors-in-javascript and https://stackoverflow.com/questions/34629226/grasping-prototypical-inheritance-through-pseudoclassical-instantiation-javascr/34629365#34629365 – Pavlo Maistrenko Nov 03 '22 at 20:11
  • The `class` version is equivalent to doing `Animal.prototype.makeNoise = function() { ...}` – Barmar Nov 03 '22 at 20:17
  • Just a heads up, if your new to JS, the need for classes is much less than say other OOP languages like C++/ Delphi/ C# etc, Due to JS having really good scope & closures, you will find classes don't add much to the table. The only time you will find they are useful is if you create lots of instances, think a Point object, with a dist method etc. I would say these days 95%+ of my code lacks any classes, and is much easier to code and reason with, (no need to worry about `this` and `bind` etc).. – Keith Nov 03 '22 at 20:37

0 Answers0