g-akshay
2/19/2017 - 7:53 AM

Extending JS object using prototype chain

Extending JS object using prototype chain

function extend(subClass, superClass) {
    
    var F = function() {};
    F.prototype = superClass.prototype;
    subClass.prototype = new F();
    subClass.prototype.constructor = subClass;
    subClass.superclass = superClass.prototype;
    if (superClass.prototype.constructor == Object.prototype.constructor) {
        superClass.prototype.constructor = superClass;
    }
}
function Person(name) {
    this.name = name;
}
Person.prototype.getName = function() {
    return this.name + '-parent';
}

function Author(name, books) {
    Author.superclass.constructor.call(this, name);
    this.books = books;
}

extend(Author, Person);

Author.prototype.getBooks = function() {
    return this.books;
};

// overriding parent method
Author.prototype.getName = function(){

    var authorName = this.name;
    var personName = Author.superclass.getName.call(this);

    console.log('Author name: ', authorName , 'person name' , personName);  
};

var a = new Author('somename', 'bookname');

a.getName();