Friday, November 6, 2009

More Java Script: Object Oriented Programming in JavaScript

While early adopters of JavaScript used it as a simple scripting engine to create dynamic web pages, modern web designers have come to use more sophisticated object oriented techniques in building their code.


Three primary goals of object oriented programming to be:



  • Encapsulation - Support for method calls on a JavaScript object as a member of a Class.

  • Polymorphism - The ability for two classes to respond to the same (collection of) methods.

  • Inheritance - The ability to define the behavior of one object in terms of another by sub-classing.


Simple Objects



The simplest object oriented construct in JavaScript is the built-in Object data type. In JavaScript, objects are implemented as a collection of named properties. Being an interpreted language, JavaScript allows for the creation of any number of properties in an object at any time (unlike C++, properties can be added to an object at any time; they do not have to be pre-defined in an object declaration or constructor).



So, for example, we can create a new object and add several ad-hoc properties to it with the following code:


obj = new Object;obj.x = 1;



obj.y = 2;



Which creates a JavaScript object which I will represent graphically like this:

Obj
x 1
y 2

Object.prototype

constructor Object



The left hand column displays the property name of each available property on the object, while the right hand column displays it's value. Note that in addition to the x and y properties that we created, our object has an additional property called constructor that points (in this case) to an internal JavaScript function.



Prototypes



In JavaScript, each Object can inherit properties from another object, called it's prototype. When evaluating an expression to retrieve a property, JavaScript first looks to see if the property is defined directly in the object. If it is not, it then looks at the object's prototype to see if the property is defined there. This continues up the prototype chain until reaching the root prototype. Each object is associated with a prototype which comes from the constructor function from which it is created.



In FireFox and in ActionScript, an object's prototype can be explicitly referenced via the non-standard __proto__ property. But in standard JavaScript a prototype object can only by directly referenced through the object's constructor function object.



[According to: http://mckoss.com/jscript/object.htm]

No comments:

Post a Comment

Followers