Prototype inheritance

by ozzymcduff

HTML

<div id="consolelog"></div>

JavaScript

// Declaring our Animal object
var Animal = function () {};
Animal.prototype.name = 'unknown';
Animal.prototype.getName = function () {
    return this.name;
};


// Declaring our Dog object
var Dog = function () {
    // A private variable here        
    var private = 42;
};
// Dog extends animal
Dog.prototype = new Animal();
// overriding the name
Dog.prototype.name = "Bello";
// Implementing ".bark()"
Dog.prototype.bark = function () {
    return 'MEOW';
};



// -- Done declaring --

// Creating an instance of Dog.
var dog = new Dog();
// Proving our case
$("#consolelog").html(
    ["Is dog an instance of Dog? ", dog instanceof Dog, "\n",
    "Is dog an instance of Animal? ", dog instanceof Animal, "\n",
    dog.bark() +"\n", // Should be: "MEOW"
     'Should be: "MEOW"',
    dog.getName() +"\n", // Should be: "Bello"
     'Should be: "Bello"',
    dog.private +"\n", // Should be: 'undefined'
    "Should be: 'undefined'"
    ].join("\n<br>")
);