JSFiddle - React, Tailwind, and code Playground

by cettox

JavaScript

function Farm(animalList, _farmer){
    var animals = [];
    this.lastToSpeak = "";
    this.farmer = _farmer;
    var self = this;
    function Cow(){
        this.speak = function(){
            alert("I'm a Cow and I belong to "+self.farmer);
        }
        lastToSpeak = "A Cow";
    }
    
    function Sheep(){
        this.speak = function(){
            alert("I'm a Sheep and I belong to "+self.farmer);
        }
        lastToSpeak = "A Sheep";
    }
    
    for(var i = 0; i < animalList.length; i++){
        switch(animalList[i]){
            case "Cow":
                animals.push(new Cow());
                break;
            case "Sheep":
                animals.push(new Sheep());
                break;
            case "Goat":
                animals.push(new this.Goat(self.farmer));
                break;
        }
    }

    this.allSpeak = function(){
        for(var i = 0; i < animals.length; i++){
            animals[i].speak();
        }
    }
}

Farm.prototype.Goat = function(farmer){
    
    this.speak = function(){
        alert("I'm a Goat and I belong to "+farmer);
    }
    this.lastToSpeak = "A Goat";
    
}

myFarm = new Farm(["Cow","Goat"],"Old MacDonald");
myFarm.allSpeak();