Tag Archives: oop

JavaScript Prototypal Inheritance Pattern

This is pretty basic stuff but I’ll just place it here in case someone searches for a way to achieve inheritance in JavaScript.

 

// JavaScript doesn't have classes but same behavior can be easily obtained using functions
// Let's consider a class Person
function Person() {
    this.name   = '';
    this.birth  = {
        'year':  -1,
        'month': -1,
        'day':   -1
    };
}

// Basic setters and getters for the class attributes
// I'll skip the validation since we're not focusing on that now
Person.prototype.set_name = function(name) {
    this.name = name;
};

Person.prototype.set_birth = function(year, month, day) {
    this.birth.year  = year;
    this.birth.month = month;
    this.birth.day   = day;
};

Person.prototype.get_name = function() {
    return this.name;
};

Person.prototype.get_birth = function() {
    return this.birth.day + '/' + this.birth.month + '/' + this.birth.year;
};

// Student Class
function Student() {
    this.school = '';
}

// We inherit all properties from the Person Class
Student.prototype = new Person();

// We need to set the constructor otherwise Student instances would have Person constructor
Student.prototype.constructor = Student;

// Student setters and getters
Student.prototype.set_school = function(school) {
    this.school = school;
};

Student.prototype.get_school = function() {
    return this.school;
};

Usage of above described classes:

// New Student instance
var student1 = new Student();

student1.set_name('Catalin');
student1.set_birth(1900, 1, 1);
student1.set_school('A.I.Cuza');

console.log(student1.get_name());
console.log(student1.get_birth());
console.log(student1.get_school());