Wednesday, August 02, 2006

Object Oriented Programming In Javascript


1. Object Oriented Programming Goal:
a. Encapsulation
b. Polymorphism
c. Inheritance

2. Objects in Javascript
Object in javascript is collection of names properties, javascript allows for the creation of any number of properties in an object at any time. For example:
obj = new Object; // constructor -> Object
obj.x = 1; // ad-hoc property x
obj.y = 2; // ad-hoc property y

3. Define a Class - Object Constructor
A new Javascript class is defined by creating a simple function using operator "new". For example:
function Foo()
{
this.x = 1;
this.y = 2;
}
obj = new Foo;

4. What is Prototype
Used in inheritance. In javascript, object can inherit properties from another object (prototype). We could say, Prototype = parent class. Prototype means that if a class is inherited from another class, then it can borrow all of its methods, so we don't need to redefine them. (look at http://webdevelopersjournal.com/articles/jsintro3/js_begin3.html)

5. Define and call methods in a class
a. Assign functions to a constructor's protoype
function Foo()
{
this.x = 1;
}
Foo.prototype.AddX = function (y)
{
this.x += y;
}
obj = new Foo;
obj.Add(5);

6. Define a sub-class
Standard paradigm is to use the prototype chain to implement the inheritance of methods from a super class.
function A() // define super class
{
this.x = 1;
}
A.prototype.Doit = function ()
{
thisx += 1;
}
B.prototype = new A; // define sub-class
B.prototype.constructor = B;
function B()
{
A.call(this); // call super-class constructor
this.y = 2;
}
B.prototype.DoIt = function ()
{
A.prototype.DoIt.call(this);
this.y + = 1;
}
b = new B();
b.DoIt();

7. Private memebers in Javascript
Variables defined in the constructor will persist beyond the lifetime of the construction function itself. To access these variables, you need to create local functions within the scope of constructor.
function A()
{
var x = 7;
this.GetX = function () {return x;}
}

obj = new A;
obj.getX();


--------------------------------------
References:
1. http://mckoss.com/jscript/object.htm
2.http://webdevelopersjournal.com/articles/jsintro3/js_begin3.html

0 Comments:

Post a Comment

<< Home