Javascript prototypes and private vars examples

by Riffic

JavaScript

/**Javascript prototypes with private vars example*/

function Animal(type) {
    this.type = type;
    this.init();
}

Animal.prototype = (function() {
    var typeCount = []; //Private static var in comparison to other langs
    return {
        constructor: Animal,
        init: init,
        getAmount: getAmountPrivate
    };

    function getAmountPrivate() {
        var isAre = typeCount[this.type] > 1 ? "are" : "is";
        return "There " + isAre + " " + typeCount[this.type] + " " + this.type + ( isAre === "are" ? "s" : "");
    }

    function init() {
        typeCount[this.type] ? typeCount[this.type]++ : typeCount[this.type]= 1;
    }

})();
Animal.prototype.getAmountPublic = function() {
    return "There are " + privateCount + this.type + "(s)";
};


var animalOne = new Animal("Cat");
console.log(animalOne.getAmount()); //There is 1 Cat
var animalTwo = new Animal("Dog");
console.log(animalTwo.getAmount()); //There is 1 Dog
var animalThree = new Animal("Dog");
console.log(animalThree .getAmount()); //There are 2 Dogs