Skip to content
Amal Hashim
All posts
Article

JavaScript - Object Oriented Programming

A short tour of object oriented JavaScript: constructors, properties, prototype methods and single inheritance.

2 min read#JavaScript

JavaScript use is growing fast, so it is a good time to learn how to write clean and organised code instead of loose scripts. This post covers some concepts worth knowing.

JavaScript is a prototype based language. It supports object oriented programming, but it has no classes.

Classes and constructors

Defining a "class" means creating a function:

js
function Employee() {
}

Create an instance with new:

js
var e = new Employee();

Creating an object runs the statements inside the function, so the function acts as a constructor:

js
function Employee() {
    alert("I am an employee");
}
var e1 = new Employee();

This brings up an alert window.

Alert window shown when the Employee object is created

Properties and methods

Properties are variables set on the object. Inside the function, refer to them with the this keyword, much like C#.

js
function Employee(name) {
    this.name = name;
}
var e1 = new Employee("Amal Hashim");
alert("I am an employee with name = " + e1.name);

Alert showing the employee name

Methods are functions added to the prototype. You call them in the same way you read properties:

js
function Employee(name) {
    this.name = name;
}
Employee.prototype.getName = function() {
    alert(this.name);
};
var e1 = new Employee("Amal Hashim");
e1.getName();

Alert shown by the getName method

Inheritance

JavaScript supports single inheritance, which lets you build parent and child relationships.

js
// Define parent class
function Employee(name) {
    this.name = name;
}
Employee.prototype.whoAmI = function() {
    alert("Employee Object");
};
Employee.prototype.getName = function() {
    return this.name;
};

// Define child class
function Manager() {
    // Invoke parent constructor
    Employee.call(this);
}
// Inheritance - Manager inherits Employee
Manager.prototype = new Employee();
Manager.prototype.constructor = Manager;
// Override whoAmI
Manager.prototype.whoAmI = function() {
    alert("Manager Object");
};

var manager = new Manager();
manager.whoAmI();
manager.name = "Amal Hashim";
alert(manager.getName());
// Checking
alert(manager instanceof Manager);
alert(manager instanceof Employee);

The alerts show "Manager Object", the name, and then true twice.

Alert from the overridden whoAmI method on the Manager object

Alert showing the manager name, Amal Hashim

Note that Manager does not define getName. It gets the method from the parent Employee through the prototype chain.