OOP with JavaScript

December 16, 2007

JavaScript actually implements all objects as nothing but associative arrays. We can test this in the following example. In Javascript objects can be created in many ways as follows.

  • Simple Object Creation
    • The simplest way to create an object is using keyword new Object().
    • var simpleObject = new Object();
      simpleObject.firstName = ‘Foo’;
      simpleObject.lastName = ‘Bar’;
      simpleObject.alertName = function()
      {
      alert(’My Name is : ‘ + this.firstName + ‘ ‘ + this.lastName);
      }
    • If we call simpleObject.alertName() or simpleObject.['alertName']() it will alert the firstName and lastName using concatenation
  • JSON
    • Basically we use JSON with the Ajax Request. But JSON is actually a core part of Javascript Specification. Lets build the previous example using JSON.
    • var JSONObject =
      {
      firstName : “Foo”,
      lastName : “Bar”,
      alertName : function()
      {
      alert(’My Name is : ‘ + this.firstName + ‘ ‘ + this.lastName);
      }
      };
    • Now if we call JSONObject.alertName() , the same output will be alerted as the previous one.
  • Prototype
    • Every single object in JavaScript has a prototype property associated with it. the way it works is that when you construct a new instance of an object, all the properties and methods defined in the prototype of the object are attached to the new instance at runtime
    • function PrototypeClass()
      {
      this.firstName = ‘Foo’;
      this.lastName = ‘Bar’;
      }
      PrototypeClass.prototype.alertName = function()
      {
      alert(’My Name is : ‘ + this.firstName + ‘ ‘ + this.lastName);
      }
      var prototypeObject = new PrototypeClass();
      prototypeObject.alertName(); // it will produce the same output as in the previous example.

Reference : “Practical JavaScript™,DOM Scripting and Ajax Projects”

Entry Filed under: JavaScript. Tags: , , , , .

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Me in Brief

Expert Rating Certified Professional PHP5
Hi I am Shaikhul Islam Chowdhury Shaymol,
Currently working at Internet BS Corp as a Software Engineer.
I like to explore LAMP and other Web Technologies.
 

My LinkedIn Profile

View Shaikhul Islam Chowdhury Shaymol's profile on LinkedIn
 

Pages

Categories

Links

RSS PHP Magazine

RSS PHPGeek

Archives

Photos from FlickR

graduate

RoomMates@RashidHall.KUET

faruk monir monil n me

yamin me n tani apu

me@home

More Photos