Thursday, 23 April 2015

Object Oriented JavaScript

Javascript is prototype based language, no doubt JavaScript supports OOP concepts but not the way other languages support, other languages like Python, Java, C# has concept OOP by means of Class, before we go to deep how Javascript supports OOP concepts lets check what are the difference between object oriented based programming and prototype based programming and what are the basic features of Object oriented language.

Object-oriented programming

 Object-oriented programming (OOP) is a programming paradigm that uses abstraction to create models based on the real world. OOP uses several techniques from previously established paradigms, including modularity, polymorphism, and encapsulation. Today, many popular programming languages (such as Python, Java, JavaScript, C#, C++, PHP, Ruby and Objective-C) support OOP.

OOP envisions software as a collection of cooperating objects rather than a collection of functions or simply a list of commands (as is the traditional view). In OOP, each object can receive messages, process data, and send messages to other objects. Each object can be viewed as an independent little machine with a distinct role or responsibility.

OOP promotes greater flexibility and maintainability in programming, and is widely popular in large-scale software engineering. Because OOP strongly emphasizes modularity, object-oriented code is simpler to develop and easier to understand later on. Object-oriented code promotes more direct analysis, coding, and understanding of complex situations and procedures than less modular programming methods.

Concepts of OOP

A container which lets developers bundle all functionality under a unique, application-specific name.
Defines the object's characteristics. A class is a template definition of an object's properties and methods.
An instance of a class.
An object characteristic, such as color.
An object capability, such as walk. It is a subroutine or function associated with a class.
A method called at the moment an object is instantiated. It usually has the same name as the class containing it.
A class can inherit characteristics from another class.
A method of bundling the data and methods that use the data.
The conjunction of an object's complex inheritance, methods, and properties must adequately reflect a reality model.
Poly means "many" and morphism means "forms". Different classes might define the same method or property.


Prototype-based programming

Prototype-based programming is an OOP model that doesn't use classes, but rather accomplishes behavior reuse (equivalent to inheritance in class-based languages) by decorating (or expanding upon) existing prototype objects. (Also called classless, prototype-oriented, or instance-based programming.)

The original (and most canonical) example of a prototype-based language is Self developed by David Ungar and Randall Smith. However, the class-less programming style grows increasingly popular lately, and has been adopted for programming languages such as JavaScript, Cecil, NewtonScript, Io, MOO, REBOL, Kevo, Squeak (when using the Viewer framework to manipulate Morphic components), and several others.
Let's have a look each one of this and how JavaScript support each one of this.

JavaScript object oriented programming


A namespace is a container which allows developers to bundle up functionality under a unique, application-specific name. In JavaScript a namespace is just another object containing methods, properties, and objects.

var odoo = window.odoo = {};

The idea behind creating a namespace in JavaScript is simple: create one global object, and all variables, methods, and functions become properties of that object. Use of namespaces also reduces the chance of name conflicts in an application, since each application's objects are properties of an application-defined global object.

We can also create sub-namespaces:

odoo.session = {}

Standard built-in objects

JavaScript has several objects included in its core, for example, there are objects like Math, Object, Array, and String. The example below shows how to use the Math object to get a random number by using its random() method.


Custom objects

The class

JavaScript is a prototype-based language and contains no class statement, such as is found in C++ or Java. This is sometimes confusing for programmers accustomed to languages with a class statement. Instead, JavaScript uses functions as classes. Defining a class is as easy as defining a function. In the example below we define a new class called Person.

var Session = function () {};

The object (class instance)

To create a new instance of an object obj we use the statement new obj, assigning the result (which is of type obj) to a variable to access it later.
In the example above we define a class named Session. In the example below we create two instances (session1 and session2).

var session1 = new Session();
var session2 = new Session();

The constructor

The constructor is called at the moment of instantiation (the moment when the object instance is created). The constructor is a method of the class. In JavaScript the function serves as the constructor of the object, therefore there is no need to explicitly define a constructor method. Every action declared in the class gets executed at the time of instantiation.

The constructor is used to set the object's properties or to call methods to prepare the object for use. Adding class methods and their definitions occurs using a different syntax described later in this article.
In the example below, the constructor of the class Session logs a message when a Session is instantiated.
function Session(origin, use_cors) { 
    //Assigning values through constructor 
    this.init = function (origin, use_cors) {
        this.origin = origin;   
        this.use_cors = use_cors;
    this.authenticate = function(user, password) { 
        return user +" Has authentication on " + this.origin; 
    this.init(origin, use_cors); 
//Creating session instance 
var session = new Session("http://localhost:8069", true); 
alert(session.authenticate('admin', 'password')); 

The property (object attribute)

Properties are variables contained in the class; every instance of the object has those properties. Properties are set in the constructor (function) of the class so that they are created on each instance.

The keyword this, which refers to the current object, lets you work with properties from within the class. Accessing (reading or writing) a property outside of the class is done with the syntax: InstanceName.Property, just like in C++, Java, and several other languages. (Inside the class the syntax this.Property is used to get or set the property's value.)

In the example below, we define the userName property for the Session class at instantiation:
var Session = function (userName) {
    this.userName = userName;
    console.log('Session instantiated');  

var session = new Sesion('Alice');

// Show the firstName properties of the objects
console.log('session's username is ' + session.userName); // logs "session's username is Alice"

The methods

Methods are functions (and defined like functions), but otherwise follow the same logic as properties. Calling a method is similar to accessing a property, but you add () at the end of the method name, possibly with arguments. To define a method, assign a function to a named property of the class's prototype property. Later, you can call the method on the object by the same name as you assigned the function to.

In the example below, we define and use the method welcomeMessage() for the Session class.

var Session = function (userName, firstName) { 
    this.userName = userName; 
    this.firstName = firstName;

Session.prototype.welcomeMessage = function() {
  console.log("Hello, This is" + this.firstName + ", Welcoming you to learn Javascript");

var session = new Session('mohammed', "Mohammed Shekha");

// call the Session welcomeMessage method.
session.welcomeMessage(); // logs "Hello, This is Mohammed Shekha, Welcoming you to learn Javascript"


Inheritance is a way to create a class as a specialized version of one or more classes (JavaScript only supports single inheritance). The specialized class is commonly called the child, and the other class is commonly called the parent. In JavaScript you do this by assigning an instance of the parent class to the child class, and then specializing it. In modern browsers you can also use Object.create to implement inheritance.

Note: JavaScript does not detect the child class prototype.constructor (see Object.prototype), so we must state that manually. See the question "Why is it necessary to set the prototype constructor?" on Stackoverflow.

In the example below, we define the class CharWidget as a child class of Widget. Then we redefine the render() method and add the get_value() method.

// Define the Widget constructor
var Widget = function(node, name) { = name; 
    this.node = node;

// Add a couple of methods to Widget.prototype
Widget.prototype.walk = function(){
  console.log("I am walking!");

Widget.prototype.render = function(){
    console.log("Hello, I'm " +;

// Define the CharWidget constructor
function CharWidget(node, name) {
  // Call the parent constructor, making sure (using Function#call)
  // that "this" is set correctly during the call, name);

  // Initialize our Student-specific properties
  this.subject = subject;

// Create a CharWidget.prototype object that inherits from Widget.prototype.
// Note: A common error here is to use "new Widget()" to create the
// CharWidget.prototype. That's incorrect for several reasons, not least 
// that we don't have anything to give Widget for the "name" 
// argument. The correct place to call Widget is above, where we call 
// it from CharWidget.
CharWidget.prototype = Object.create(Widget.prototype); // See note below

// Set the "constructor" property to refer to CharWidget
CharWidget.prototype.constructor = CharWidget;

// Replace the "render" method
Student.prototype.render = function(){ 

// Add a "format" method
Student.prototype.get_value = function(){
  console.log("Value of node is ", $(this.node).val());

// Example usage:
var char_widget = new CharWidget("<input type='text' name='test'></input>", "Hello World");
char_widget.render();   // "This will add input box into body and add value Hello World"
char_widget.walk();       // "I am walking!"
char_widget.get_value(); // "Hello World!"

// Check that instanceof works correctly
console.log(char_widget instanceof Widget);  // true 
console.log(char_widget instanceof CharWidget); // true



In the previous example, Student does not need to know how the Person class's walk() method is implemented, but still can use that method; the Student class doesn't need to explicitly define that method unless we want to change it. This is called encapsulation, by which every class packages data and methods into a single unit.

Information hiding is a common feature in other languages often as private and protected methods/properties. Even though you could simulate something like this on JavaScript, this is not a requirement to do Object Oriented programming.

Before going on to Encapsulation and Abstraction first we need to know what Data Hiding is and how can we achieve it in JavaScript. Date hiding is protecting the data form accessing it outside the scope. For example, In Session class we have User ID properties which should be protected. Let's see how to do it.  

function Session(uid){
    //this is private variable 
    var uid = uid;
    //public properties and functions
        timezone: "Asia/Calcutta", 
        language: "en-US", 
        getUid: function(){
            return uid;
var session = new Session(); 
//this will get undefined 
//because it is private to Session
//Will get uid value we using session's method to access its property
//funtion to get private data 


Abstraction is a mechanism that allows you to model the current part of the working problem, either by inheritance (specialization) or composition. JavaScript achieves specialization by inheritance, and composition by letting class instances be the values of other objects' attributes.

The JavaScript Function class inherits from the Object class (this demonstrates specialization of the model) and the Function.prototype property is an instance of Object (this demonstrates composition).
var foo = function () {};

// logs "foo is a Function: true"
console.log('foo is a Function: ' + (foo instanceof Function));

// logs "foo.prototype is an Object: true"
console.log('foo.prototype is an Object: ' + (foo.prototype instanceof Object));


Just as all methods and properties are defined inside the prototype property, different classes can define methods with the same name; methods are scoped to the class in which they're defined, unless the two classes hold a parent-child relation (i.e. one inherits from the other in a chain of inheritance).

Person.prototype.getInfo = function(){
 return "I am " + this.age + " years old " +
    "and weighs " + this.weight +" kilo.";
function Employee(age,weight,salary){
 this.age = age;
 this.weight = weight;
 this.salary = salary;
Employee.prototype = new Person();
Employee.prototype.getInfo = function(){
 return "I am " + this.age + " years old " +
    "and weighs " + this.weight +" kilo " +
    "and earns " + this.salary + " dollar.";  
var person = new Person(50,90);
var employee = new Employee(43,80,50000);


For detail go through:

Your inputs are welcomed to improve this post.