Sunday, August 31, 2014

Object Oriented JavaScript : Inheritance, Polymorphism and Encapsulation

Here is Previous Parts of this series:

This is the third article of the series of Object Oriented JavaScript. In previous article we have seen private, public and static types of method.

Constructor


Lets start this article with Constructor as whenever you instantiate a class, you need to initialize some default values for this we initialize values in constructor but as in JavaScript Class is nothing but a function which contains methods and properties, so whenever you instantiate an object of JavaScript function /class it call that method so whatever you have initialize within the class will automatically be set. So you no need define separate constructor.
var Student = function () {
    console.log('Instance created');
    this.prop_one = "initialized value";
    this.prop_two = "initialized value";
};


var student = new Student();
console.log(student.prop_one); //initialized value
Here is Demo

Inheritance


Inheritance is one of the key feature of Object Oriented Programming, Inheritance can be achieved with prototype property. You can create a parent class and then inherit all the public methods and properties in child class. In JavaScript you do this by assigning an instance of the parent class to the child class. In ECMAScript 5 and above you can also use Object.create() to implement inheritance.

Lets see an example of inheritance in which we define a Human class and then inherit it in Student class and override some method of Human class.
// Define the Human constructor
function Human(fullName) {
  this.fullName = fullName;
}

// Add a couple of methods to Human.prototype
Human.prototype.speak = function(){
  alert("I speak English!");
};
Human.prototype.introduction = function(){
  alert("Hi, I am " + this.fullName);
};

See fiddle demo here.

Now we will create a child class of student

// Define the Student
function Student(fullName, school, courses) {

 //To initialize or call parent class constructor we need to Human.call()  
 //for call() we need to pass this instance
 //since fullName is Human class property inherited in student so we
 //passed it to parent class
  Human.call(this, fullName);

  // Initialize our Student properties
   this.school = school;
   this.courses = courses;
};

See fiddle demo here.

To inherit it from parent Human class we will set Student.prototype

//Do not try to set new Human() here as we are not calling it here
//calling Human here need to pass fullName property which is not available here
//the correct place to call parent object is in child class constructor
//as we call it in above Student function code
Student.prototype = Object.create(Human.prototype); // See note below

// Set the "constructor" property to refer to Student
Student.prototype.constructor = Student;
As object.create() only works in browsers support ECMAScript 5 and above so to achieve this in older browser you can create your own function:
function createObject(prototype) {
    function emmptyClass() { }
    emmptyClass.prototype = prototype;
    return new emmptyClass();
}

Student.prototype = createObject(Human.prototype);
Lets see its usage:
// Example:
var student = new Student("Ahmed","NED University", "Computer Science");
student.introduction();   // "Hi, I am Ahmed"
student.speak();       // "I speak English!"

// Check that instanceof works correctly
alert(student instanceof Human);  // true 
alert(student instanceof Student); // true

See here the demo.

Polymorphism / Overriding


Polymorphism is the main pillar of Object Oriented Programming, it refers to the ability of an object to provide different behaviors in different state of objects. For example Parent class Human define a function of introduction() in which it contains simple introduction but Student object override it by adding more detailed information for introduction. So now Human() object has its own implementation of introduction and Student() has its own. It will be invoked according to the state of object.

As we inherited the Human object in Student object we can override its public methods by changing its definition.
// override the "introduction" method
Student.prototype.introduction= function(){
  alert("Hi, I am " + this.fullName + ". I am a student of " + this.school + ", I study "+ this.courses +".");
};
or you can also add new methods
// Add a "exams" method
Student.prototype.takeExams = function(){
  alert("This is my exams time!");
};

Here is usage of above overriden method:
var student = new Student("Ahmed","NED University", "Computer Science");
student.introduction();   // "Hi, I am Ahmed. I am a student of NED University, I study Computer Science."
student.speak();       // "I speak English!"
student.takeExams(); // "This is my exams time!"

// Check that instanceof works correctly
alert(student instanceof Human);  // true 
alert(student instanceof Student); // true

See demo here

Encapsulation


Encapsulation is the one of the three pillars (Encapsulation, Inheritance and polymorphism) of OOP, It is a way of structuring data and methods by concealing the implementation or internal logic of object. Like in above example Human object contains the speak() method which is available in Student object but Student object does not know about the implementation of speak() method. It is encapsulated in Human object/class, child class inherit it as it is and change the methods which is different from its parent.

Summary


In this series of article we see how beautiful and impressive JavaScript is. It is as powerful as any other Object Oriented programming language is. In above series of article I used the words like namespace, class for objects which actually do not exist in JavaScript, just to map the JavaScript to the language you are aware of it. Please write your feedback about this series of articles in comments.

You may also like to see:

Sunday, August 24, 2014

Object Oriented JavaScript : Classes, Methods and Properties

Here is Previous Part of this series:

This is second part of Object Oriented Programming in JavaScript. I would recommend to see previous article on Object Oriented JavaScript before continuing this.

JavaScript is classless, there is no class keyword in JavaScript but you can achieve same via objects.

In first part we see, how interesting JavaScript is. It allow us to work on familiar Object Oriented way of programming like we use in other programming languages. In first part we learn about namespaces, core classes, custom classes and class instances in JavaScript and there is complete article on Inheritance in JavaScript through prototyping.

In last article we see that in JavaScript class in nothing but a function. So writing a class in JavaScript is as easy as writing a function.

Public Methods & Properties


Here is a Student class with some public properties and function.
var Student = function () {
this.first_name;
this.last_name;
this.courses = [];

this.fullName = function () {
return this.first_name + ' ' + this.last_name;
};
};

var student = new Student();

student.first_name = "Ali";
student.last_name = "Raza";
student.courses = ["JavaScript", "Object Orient Programming", "Functional Programming"];
var full_name = student.fullName()
console.log(full_name);
console.log('No. of Courses : ' + student.courses.length);
Here is JsFiddle Demo

Here in this example we used this keyword with function and properties to make it public. One thing which make JavaScript more powerful from any other OOP language is run-time changes in class structure. You can add new properties and function for any particular instance of function. So lets say in above example we add some more properties and function to an object:

var Student = function () {
this.first_name;
this.last_name;
this.courses = [];

this.fullName = function () {
return this.first_name + ' ' + this.last_name;
};
};

var student = new Student();

student.first_name = "Ali";
//runtime added property not present in class
student.middle_name = "H.";
student.last_name = "Raza";
student.courses = ["JavaScript", "Object Orient Programming", "Functional Programming"];
student.skills = function () {
return "Expert in JavaScript";
}

console.log(student.skills());

Here is JsFiddle Demo

One thing to notice in above example is that we have instantiate an object of Student class using statement var student = new Student() ; so the properties and function we adding to student object is only available to current object only. So if we created another object i.e, var student2 =new Student(); and try to call the skills() function with this it will throw an error.

 

Public Methods using Prototype


You can add public methods to a class using Prototype property then it will be available to all the instances of the class.
var Student = function () {
this.first_name;
this.last_name;
this.courses = [];
};

Student.prototype.fullName = function () {
return this.first_name + ' ' + this.last_name;
};
Here is JsFiddle Demo

 

Private Method & Properties

 

In class methods and properties we remove this keyword and introduce var keyword (recommended by strict mode of ECMAScript) then it will be a private function and properties.
var Student = function () {
    var private_property = "It is private property";

    var private_function = function () {
        console.log("This is private function");
    };
};

var student = new Student();
//will print undefine
console.log(student.private_property);
//this will throw an error private_function is not a function
console.log(student.private_function());

Here is JsFiddle Demo

Note here as we discussed above you can add new properties within object after creating an instance of class so here if you assign value to private_property it will create a new property in instance and assign value to it. JavaScript will not throw error on property creation.
var student = new Student();

//will print undefine
console.log(student.private_property);

//add new property same name of private property
student.private_property="set public content";

console.log(student.private_property);
Another point here to note is that you have created a public property of same name to the private property but class still maintain the private property with same value. So I was right in saying JavaScript is a race car you only need to know how to handle it.
var Student = function () {
    var private_property = "It is private property";

    var private_function = function () {
        console.log("This is private function");
    };

    this.checkPrivatePropertyValue = function () {
        console.log(private_property);
    }
};

var student = new Student();
//will print undefine
console.log(student.private_property);

//add new property same name of private property
student.private_property = "set public content";

console.log(student.private_property);
student.checkPrivatePropertyValue();
Here is JsFiddle Demo

Static Functions


To create a Static method for the class, you can add it with the class name.
var Student = function () {
    this.first_name;
    this.last_name;
    this.courses = [];
};

Student.StaticMethod = function () {
    return "Here is static content";
};
Here is JsFiddle Demo

Now you can call it anywhere directly with the class name.

So in this article we explore to declare the different type of methods and properties. If you have any feedback please do write comments.

Here is Next Part of this series:

Thursday, August 14, 2014

Object Oriented Programming & JavaScript

You may also like to see:

JavaScript is an excellent programming language. It is a race cars with so many gears, you just need to know how to handle it. JavaScript supports Object Oriented programming, it will not force it while compiling by throwing errors. But if you know how to write OOP code with JavaScript you can get all the aspects of OOP in JavaScript and believe me its amazing.


JavaScript supports object oriented programming because it supports properties, methods, inheritance through prototyping which are building blocks of OOP. Many developers avoid JavaScript because they are used to off writing OOP code with C#, Java or any other OOP programming languages and they don't know that JavaScript supports OOP and once you start writing code with JavaScript, It gives you encapsulated, re-usable and well managed object oriented code.

JavaScript Object Oriented Programming

Namespace


If you are C# or Java developer you must be familiar with Namespace. Namespace is a logical group of classes containing similar functionality under a unique name.In JavaScript Namespace is an object(namespace) which contains other objects, functions (classes). There is no difference in Namespace object and class object used in JavaScript unlike C# or other OOP languages.

Here is an example of namespace
// global namespace
var OOPJS = OOPJS || {};
Here in above code it is checking if namespace(object) of OOPJS is already existed within applications then use the same object but if it is not created then it create an empty object and initialize our object(namespace). Now this namespace is ready to contain the classes(function) and properties.

You can write your namespace helping function or common variables, functions across the namespace within this namespace.
// Create container called OOPJS.Helpers for common methods

var OOPJS = {};
OOPJS.Helpers = {

    //common variables
    global_variable: "Object Oriented Programming",

    //common methods
    myNamespace: function () {
        return "OOPJS";
    }
}
console.log(OOPJS.Helpers.global_variable);
console.log(OOPJS.Helpers.myNamespace());


See here demo.

Core Classes/Objects

JavaScript has many object (classes) available for use, like in C# there is Math object which contains static function abs(), round() etc, same concepts available in JavaScript. There are objects like Math, Object, Array, Number, Date, JSON, String and others.

See here a math object random() function which generate a random value.
console.log(Math.random());


Like Math there is object Object available which contains  prototype, create() [ECMAScript 5 and above] and many others. Since specified built-in objects have the object referred to by Object.prototype in their prototype chain by default therefore all the properties and functions of Object is inherited to that object. Note all these methods and properties also inherited to namespace too since it is also an object.

So if you want to add a function to all the objects, you can add it to Object using prototype property.

Custom Classes/Objects

The Class
JavaScript contains no separate class declaration like C#, Java or other programming languages. In JavaScript class is a function which contains methods and properties.

Here is a class declaration:
function Person() { } 
//or 
var Student = function(){ }
Class Instance
To create an instance of class we use new keyword with the class name, which instantiate a new fresh instance of class.


Here we declare a class and then created two instance of the class.
function Student() { }
var student1 = new Student();
var student2 = new Student();

In next article we will see classes in details with different access modifiers and other aspects of Object Oriented Programming in JavaScript. Please comment your valuable feedback and suggestion for improvement of this post.

Here is Next Part of this series:
Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,