June 16, 2014

Classical Inheritance in JavaScript


By using prototype and constructor properties, inheritance in Javascript is possible.
The prototype property allows you to add properties and methods to an object.

Example  


function Person(theName, theEmail) {
    this.name = theName;
    this.email = theEmail;
}
Person.prototype = {
    constructor: Person,
    changeEmail: function (newEmail) {
        this.email = newEmail;
        return "New Email Saved: " + this.email;
    }
};

function User() {
    this.quizScores = [];
    this.currentScore = 0;

}
User.prototype = new Person("", "");
User.prototype.constructor = User;
User.prototype.saveScore = function (theScoreToAdd) {
 this.quizScores.push(theScoreToAdd);
User.prototype.showNameAndScores = function () {

    var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
    return this.name + " Scores: " + scores;
};

How to use it

user = new User();
user.changeEmail("test@noserver.net");

The result is the value of the inherited property "email"  is "test@noserver.net";