Web Developer and Author

code

JavaScript Object Inheritance

Inheriting an object in JavaScript

Lets take a look at how object inheritance is handled in JavaScript (ES5)

//Our Base object
var animal = function(containerId){
    this.container = containerId;
    this.kind = "animal";
    this.noise = "roar";
};
animal.prototype.goes = function(){
    var container = document.getElementById(this.container);
    container.innerHTML += "the " + this.kind + " goes " + this.noise;
}
//Our object that will inherit
var dog = function(containerId){
    //call the animal constructor function but bind it to the dog's "this" keyword
    animal.call(this, containerId);
    //override the dog's inherited parameters
    this.kind = "dog";
    this.noise = "woof";
}
//assign the dog's prototype to a duplicate of the animal's prototype
dog.prototype = Object.create(animal.prototype);

//create an instance of a dog
var spot = new dog("example1");
spot.goes();
javascriptBLC