Wednesday, December 26, 2012

How to create Objects in Javascript



JavaScript is an object oriented language. In-spite  of being class based , it is prototype based language, where we can create the prototype of specific objects.

Java script provides us three ways to create objects -
1- Direct instance using JSON ( Java Script Object Notation) syntax - In this way we do not create the prototype but direct object.
The sample code is as mentioned below -

var jsonObject = {
            text : "Json Object has been accessed ",
                  numberOfTimes : 0
  };


2- Direct instance using Object - In this way, we do not create prototype but direct object.
The sample code is as mentioned below -

  var directObject = new Object();
  directObject.text = "Direct created Object has been accessed ",
  directObject.numberOfTimes = 0;

3- Instance from prototype - In this way we create prototype and then create instances based on the prototype. This approach is beneficial when we want to create multiple objects based on the same prototype in the same application or want to use this prototype as utility.
The sample code  is as mentioned below -
function prototypeTest()
 {
    this.text;
    this.numberOfTimes;
 }
 var prototypeObject = new prototypeTest();
 prototypeObject.text="Object created through prototype has been accessed ";
 prototypeObject.numberOfTimes=0;


References -
http://www.w3schools.com/json/json_syntax.asp
http://www.w3schools.com/js/js_objects.asp
http://www.json.org/
 
  

No comments:

Post a Comment