Empty JavaScript functions

I’m just wondering about what the lines ‘function Animal() { }’ and ‘function Bird() { }’ are for when the functions are wrapping anything?

function Animal() { }
Animal.prototype.eat = function() {
  console.log("nom nom nom");
};
function Bird() { }
Bird.prototype = Object.create(Animal.prototype);
Bird.prototype.constructor = Bird;

Think of Animal as the pattern, the “blueprint” used to create each instance of Animal. Defining the function of telling Javascript what to do when we say

const octopus = new Animal();

The function simply defines the shape of that new thing, the instance of our constructor. An empty function creates an empty object (no properties) that is wired to the constructor’s prototype. Doing this, the instance can use any of those prototype methods or properties.

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect