Pages

Tuesday, November 4, 2008

Javascript Object Oriented Programming

Javascript is a prototype based language (not a class based language). You can read more here to understand differences between prototype based and class based language.

However, prototype has some good features that help you can implement the Object oriented programming model. Nowadays, a lot of javascript frameworks support us can implement OOP easily (like Prototype, JQuery, …). In this post, I do not want to introduce about them. I would like to help you understand about Javascript OOP without any support from other external libraries or frameworks.

Index

1. Defining a class

2. Common definitions and implementation

3. Inheritance in Javascript

1. Defining a class

To define a class in Javascript, we can use one of below ways

1. Traditional way

function className ([params] ) {

//properties and functions

}

2. Second way

className = function( [params]) {

//properties and function

}

2. Common definitions and implementation

  • private variables are declared with the ‘var’ keyword inside the object, and can only be accessed by private functions and privileged methods.Example
    function Person {
    var name = “KBird”;
    }
  • private functions are declared inline inside the object’s constructor (or alternatively may be defined via var functionName=function(){}) and may only be called by privileged methods (including the object’s constructor).Example
    function Person {
    this.name = “KBird”;
    var getName = function()
    {
    return this.name;
    }
    };
  • privileged methods:privileged methods are declared with
    this.methodName=function
    (){}
    and may invoked by code external to the object.
  • public properties are declared with this.variableName and may be read/written from outside the object.
  • public methods are defined by Classname.prototype.methodName = function(){} and may be called from outside the object.
  • prototype properties are defined by Classname.prototype.propertyName = someValue
  • static properties are defined by Classname.propertyName = someValue

3. Inheritance in Javascript

Inherit from a super class

subclassName.prototype = new subClass;

Override a function

subclassName.prototype.functionNeedToOverride =function(params) {

}

To be continue

Reblog this post [with Zemanta]

No comments: