New object instance vs new class instance vs subclassing - when to use what?


#1

How do I decide on which method to use when creating a chain of items? For example, here are 3 methods that are equally valid:

Method 1 - creating new instances of an object

const Food = function(cuisine,name){
      this.cuisine = cuisine;
      this.name = name;
}

Food.prototype.sayYum = function(){
     console.log(`this is so delicious!`);
}

const padThai = new Food('thai','padThai');

Method 2 - creating a new class

class Food{
constructor(cuisine,name){
this.cuisine=cuisine;
this.name=name;
}

    sayYum(){
       console.log(`this is so delicious!`);
    }
}

const padThai = new Food(‘thai’,‘padThai’);

Method3 - creating a child class

class Food{
     constructor(cuisine,name){
         this.cuisine = cuisine;
         this.name = name;
     }

    sayYum(){
       console.log(`this is so delicious!`);
    }
 }

class Thai extends Food {
     constructor(name){
        super(name);
     }

}

const padThai = new Thai(‘padThai’);

Let’s say I’m creating a directory for restaurants, what’s the best way out of the three to do it?


#2

Most of the time you probably shouldn’t be subclassing, if you need functionality of another type, include such a value in the object instead of subclassing

Classes don’t introduce anything new, it’s mostly just syntax, it’s still prototypes underneath. Classes “do it right”, so you should probably prefer them over using functions with new for creating objects, and setting stuff on that function’s prototype. If you need to break away from what class syntax does, or you have some other argument for using functions, then go for it.

Not much of a clue what you mean by a directory for restaurants. You might want to put data about each one in objects? And if there are multiple restaurants you might want to store those in an array or perhaps a Map