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”