Javascript OOP – Basics

Javascript is by far the most misunderstood language ever created. It was the language created for scripting web pages to provide very basic interaction to the user. But with the advent of  very powerful javascript engines in all modern browsers, The landscape for creating rich internet applications increased almost exponentially and the true gems of language came into limelight.  Douglas Crockford a well known Javascript guru describes the salient features of language here and he call the language as

The World’s Most Misunderstood Programming Language

In this article I am trying to revisit the object oriented programming capabilities of the language. Most of the readers who are already familiar with OOP concepts with either C++ or Java may have to unlearn everything they know about OOP and should approach Javascript with a clean mind! Believe me or not all the OOP concepts in Javascript are modeled just with one keyword the function. The beauty of the language is appreciated only when you start realizing the language capabilities which combines concepts from functional programming and object oriented paradigm almost seamlessly.

Ok lets get started. Readers who are not familiar with the basics of the language can refer the link 1 in the reference section at the end of the article.

Class And Object Creation

Unlike most OOP languages javascript doesn’t have a separate keyword for creating a class. Like I said before it reuses the function keyword.

var Person = function(){
};

This is how you create a class in javascript. May seem exactly same as how a function is declared. Yes of course, In javascript classes are modelled with functions. The difference comes when you instantiate a class into object.

//invokes the function
Person();

/* creates an object of type Person and
invoke the function of the instantiated object */
new Person();

Currently the Person class doesn’t have any useful stuff to play with so lets add some members and methods to it.

var Person = function(){
	//This is how we declare members of a class
	this.age = 26;
	//This is how we declare a methods of a class
	this.printAge = function(){
		console.log('Age is: '+this.age);
	};
};

this keyword has the usual meaning as in other programming language. It refers to the current object that is created. There are some gotchas regarding the use of this though, We will get back to it later. If you observe closely both this.age and this.printAge  are variables but one points an integer object and other points to a function. In Javascript functions are used as first class citizens. Functions can be declared inside other functions, Functions can be assigned to variables, Functions can be passed returned from within the functions the list goes on and on.

There is another way of declaring the members of a class

var Person = function(){
};
//for the time being ignore what prototype is
Person.prototype.age = 26;
Person.prototype.printAge = function(){
	console.log('Age is: '+this.age);
};

Assessing object members

var vineel = new Person();

//this is how we access object variables and methods
vineel.age = 35;
vineel.printAge();

In the above code var  is the keyword used to create a variables(local). Also important to remember that when ever we access a member variable from a member function we need to use the this keyword before member variable. This can be observed in printAge function.

Private object members

Some properties like salary inside Person class may not have access to outside world. This can be achieved with the var  keyword.

var Person = function(){
	//This salary will be invisible outside the class
	var salary = 10000000;
	//Private helper function not visible outside the class
	var hike = function(){
		salary += 10000;
	};
	//functions with in the class can access the local members
	this.spend = function(){
		console.log('Spending.... '+salary);
		hike();
	};
};

var vineel = new Person();
//cannot access local members directly
vineel.salary; //undefined
vineel.hike(); //undefined
//print the salary
vineel.spend();

Basically var simulate public and private access modifier behaviour that is well known in other programming language.

Javascript is an interpreted language so all the properties that are declared inside the Person class are created only when you create an Object with new keyword or when you directly invoke Person as a function

Creating static members

Yet times many objects have to share a common data or a common method, This type of common data which is not associated with any one particular object but accessible to every one of the object is called static data. Following example will clearly illustrate the use case.

var Account = function(){
	this.balance = 200000;
	this.printBalance = function(){
		console.log('Balance.... ' + this.balance);
	};
};
//observe no prototype here
Account.MinimumBalance = 1000;
Account.PrintMinimumBalance = function(){
	console.log(Account.MinimumBalance);
}

Creating object constructors

Constructors are methods of the class which will be automatically called when the object is created. These are very helpful in providing the object a meaningful state.

var Person = function(name, age){
	//This simulates constructor functionality in other programming languages
	this.name = name;
	this.age = age;

	this.printName = function(){
		console.log('Name is: '+this.name);
	};

	this.printAge = function(){
		console.log('Age is: '+this.age);
	};
};

//This is how we pass information to the object being created
var vineel = new Person("vineel", 26);
var ram = new Person("ram", 34);

vineel.printName(); //prints "vineel"
ram.printName(); //prints "ram"

Gotchas with global variables

variable declared without a var statement or this statement are automatically hosted as global variables so in the following code

Global variables In Javascript
Global variables In Javascript

Every global function we create in the language is added to global namespace. This global namespace in every browser happens to be the window object. Hence even though we invoke a function like alert()  this actually refers to window.alert() similarly in step 1 above Person() refers to window.Person() 

Gotchas with this

//Use of this inside function declaration.
//Improper use can polute global namespace or
//May lead to undefined reference errors
var Person = function(age){
	//This is how we declare members of a class
	this.age = age;
};
var p1 = new Person(20);
// in the Person function this.age refers to p1 object age
var p2 = new Person(40);
// in the Person function this.age refers to p2 object age
Person(30);
// in the Person function this.age refers to global object age and this is associated with window object
// the last call polutes the global window object.
// we can verify this as below
console.log(window.age);// prints 30

We just touched the surface of the language from OOP standpoint. I would like to discuss inheritance and talk about prototypes and the internals of the inheritance in a follow up article.

References:

  1. Douglas Crockford: “The JavaScript Programming Language” (1 of 4)(Google)
  2. Douglas Crockford: “The JavaScript Programming Language” (2 of 4)(Google)
  3. Douglas Crockford: “The JavaScript Programming Language” (3 of 4)(Google)
  4. Douglas Crockford: “The JavaScript Programming Language” (4 of 4)(Google)
  5. https://developers.google.com/chrome-developer-tools/

One thought on “Javascript OOP – Basics

Leave a Reply