Wednesday, September 18, 2013

Javascript objects

In JavaScript, almost everything is an object. All primitive types except null and undefined are treated as objects. They can be assigned properties and they have all characteristics of objects. Javascript is object based programming language (Prototype-based programming). First time when I heard, JS is OO programming, I was surprised and can't find and class, interface, etc such keywords. Later, I found, it's different. See below,
var jsObj = new Object();
jsObj.property1 = "Value1";
jsObj.property2 = "Value2"
That's how we create object and use properties. Alternative way to accessing properties,
myCar["property1"] = "Value1";myCar["property2"] = "Value2"; 
Aren't they associative arrays?Yes, you are right!Javascript Objects are sometimes called associative arrays.
Another way for creating objects in javascript,

var obj = { 'property1':   "Value1",  
            'property1': "Value2"};// property1 can be number, string or identifier
Methods in javascript,
Constructor - function are methods and it's constructor,
function f1(){
  //function itself is a constructor of object
}
Confused?Let's see below,
function Jsobject(pro1, pro2, pro3) {
  this.pro1 = pro1;
  this.pro2 = pro2;
  this.pro3 = pro3;
}
this above means current object (instance). Like this in java and any other object oriented programming.
var myvar = new Jsobject("Value1", "Value2", "Value3");
Isn't myvar is object?So, isn't function constructor?Alternate way to access properties,
myvar.pro1 = "Value1";
It can be chained like,
Vehicle.scooter.numWheels = 2;
What about methods?See below,
var objMethods = {
  method1: function(params) {
    //body of method here
  }
};
You can assign method to an variable. Suppose you defined function with name method1 then you can assign as below,
this.method = method1;
As always more coming soon. Keep coming here.

No comments:

Post a Comment