Objects creation

1) Creating the objects with new keyword

function Animal(name,sound) {
    this.name = name;
    this.sound = sound;
}

const cat = new Animal("Cat", "Meow")
const dog = new Animal("Dog", "Bow Bow")

console.log(cat.name) // Cat
console.log(dog.sound) // Bow Bow

2) Creating the objects by writing a function of customNew which takes function as arguments and simulates a new keyword.

function customNew(fn, ...args) {
    const obj = {};

    fn.call(obj, ...args);

    return obj
}

function Animal(name,sound) {
    this.name = name;
    this.sound = sound;
}

const cat = customNew(Animal, "Cat", "Meow")
const dog = customNew(Animal, "Dog", "Bow Bow")

console.log(cat.name) // Cat
console.log(dog.sound) // Bow Bow

3) Create an object with class

class Animal {
  constructor(name, sound) {
    this.name = name;
    this.sound = sound;
  }

  getName() {
    return this.name;
  }

  getSound() {
    return this.sound;
  }
}

const cat = new Animal("Cat", "Meow");
const dog = new Animal("Dog", "Bow Bow");

console.log(cat.getName()); // Cat
console.log(dog.getSound()); // Bow Bow