JavaScript Class and Object

JavaScript Class

As a web developer we all know javascript as a language has variables,functions, operators facility. But we don’t know it has classes also though we are using it.So let’s understand a brief overview of class in javascript.

  • Define a class in JavaScript
    function Rectangle(height,width){
        this.height = height;
        this.width = width;
    
    }
    
    var  rectangle1 = new Rectangle(20,10);
    alert(rectangle1.height);
    

See in above code you will see Rectangle class, you thought it’s a function, yes it is a function but see in below line you can use it as a class. You can create objects from this class and access it’s members.

You can also include member methods if you wish as mentioned below:

function Rectangle(height,width){
    this.height = height;
    this.width = width;
    this.calculateArea = function(){

        return (this.width * this.height);
    };
}
var  rectangle1 = new Rectangle(20,10);
alert(rectangle1.calculateArea());

So in conclusion you can define class as the way you define in other OO languages like Java,C# .

JavaScript Object

Object is javascript is represent as JSON. Json is nothing but a notation of a key value pair.

var user = {
"id": 1,
"user_name": "ahesanali",
"email": "ahesanali.suthar@gmail.com"
};

alert(user.id);
alert(user.user_name);
alert(user.email);
alert(user['user_name']);

You can access JSON by . operator or their property name inside brackets[].

  • Alter the attribute also as mentioned below:
    user.email = "ahesan23@gmail.com";
    
  • Nested objects
    var user = {
    "id": 1,
    "user_name": "ahesanali",
    "email": "ahesanali.suthar@gmail.com",
    "items": [
    {
      "id":1,
      "item_name": "Chair",
     "price" : 2000.00
    },
    {
      "id":2,
      "item_name": "Table",
     "price" : 4000.00
    },
    {
      "id":3,
      "item_name": "Table Legs",
     "price" : 1500.00
    }
    
    ]
    };
    

There are lot of things to learn about JSON but i think for introduction this is enough and as much you use it you will get a lot.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s