Object Oriented Programming in JavaScript

Published on: March 22, 2014 Written by: Thokozani Mhlongo

Today we are going to be using the OOP approach in Javascript. It's fairly simple to do actually and this post will be very short. In most languages you create what you call a "class" with instance variables and methods. In javascript its a bit similar, except that you do not use the keyword "class". You just declare a function, and inside that function you declare your instance variables and behaviours.

An example

function Person() {
    this.name = null;
    this.date_of_birth = null;
    
    this.setName = function(name) {
        this.name = name;
    };
    this.setDateOfBirth = function(dob) {
        this.date_of_birth = dob;
    };
    this.getName = function() {
        return this.name;
    };
    this.getDateOfBirth = function() {
        return this.date_of_birth;
    };
}

The class above is quite straight-forward. Just two instance variables with functions to set and get each of them.

Using it

var person = new Person();
person.setName("Thokozani");
person.setDateOfBirth("15/08/1991");

var dob = person.getDateOfBirth();

 

Comments