JavaScript - Object Oriented Programming
A short tour of object oriented JavaScript: constructors, properties, prototype methods and single inheritance.
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:
function Employee() {
}
Create an instance with new:
var e = new Employee();
Creating an object runs the statements inside the function, so the function acts as a constructor:
function Employee() {
alert("I am an employee");
}
var e1 = new Employee();
This brings up an alert window.

Properties and methods
Properties are variables set on the object. Inside the function, refer to them with the this keyword, much like C#.
function Employee(name) {
this.name = name;
}
var e1 = new Employee("Amal Hashim");
alert("I am an employee with name = " + e1.name);

Methods are functions added to the prototype. You call them in the same way you read properties:
function Employee(name) {
this.name = name;
}
Employee.prototype.getName = function() {
alert(this.name);
};
var e1 = new Employee("Amal Hashim");
e1.getName();

Inheritance
JavaScript supports single inheritance, which lets you build parent and child relationships.
// 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.


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