Classical OOP

by Csaba Hellinger

JavaScript

(function () {
    "use strict";
    
    console.clear();

    // Animal
    function Animal(name) {
        this.name = name;
        this.legs = 0;
    }
    Animal.prototype.hello = function animal_hello() {        
        console.log("Hello, I'm " + this.name + ".");
    };
    Animal.prototype.countLegs = function animal_countLegs() {
         console.log("I have " + this.legs + " legs.");
    };

    // Dog    
    function Dog(name) {
        Animal.call(this, name);
        this.legs = 4;
    }
    Dog.prototype = Object.create(Animal.prototype);
    Dog.prototype.constructor = Dog;
    Dog.prototype.bark = function dog_bark() {
        console.log("Wooff!");
    };
    
    // Spider
    function Spider(name) {
        Animal.call(this, name);
        this.legs = 8;
    }
    Spider.prototype = Object.create(Animal.prototype);
    Spider.prototype.constructor = Spider;
    Spider.prototype.web = function spider_web() {
        console.log("I'm making a web...");
    };
    
    // Snake
    function Snake(name) {
        Animal.call(this, name);
    }
    Snake.prototype = Object.create(Animal.prototype);
    Snake.prototype.constructor = Snake;
        
    
    var dog = new Dog("Rex");
    dog.hello();
    dog.bark();
    dog.countLegs();
    console.log("I'm an animal:", dog instanceof Animal);
    console.log("I'm a dog:", dog instanceof Dog);
    console.log("I'm a spider:", dog instanceof Spider);
    
    console.log("");
    
    var spider = new Spider("Bob");
    spider.hello();
    spider.web();
    spider.countLegs();
    console.log("I'm an animal:", spider instanceof Animal);
    console.log("I'm a dog:", spider instanceof Dog);
    console.log("I'm a spider:", spider instanceof Spider);
    
    console.log("");
    
    var snake = new Snake("Kaah");
    snake.hello();
    snake.countLegs();
    
    
    
    
})();