Javascript object example

Object in Real world:

A real world entity. Every real world object/entity has two characteristics state and behavior. Let us take the example of a car. Its state is defined by color, current speed etc and behavior is defined by changing speed, applying breaks etc.

A programming language is said to be an Object Oriented Programming if it follows following OOPs principles:
1. Abstraction.
2. Encapsulation.
3. Polymorphism.
4. Inheritance.

JavaScript is an Object Oriented Programming (OOP) language. Although JavaScript does not have any class, we can direct create JavaScript object. Everything in JavaScript is an object.

How to create javascript object:

1. By object literal.
2. By object constructor.
3. By User-Defined Function.

By object literal:

Syntax:

objectName={property1:value1,property2:value2.....propertyN:valueN}

Example:

<html>
<body>
<script>  
student={rollNo:"MCA/07/06",name:"Jai"}  
document.write("Name: " +student.name + "</br>");  
document.write("RollNo: " + student.rollNo);  
</script>
</body>
</html>

Try it:

JS Bin on jsbin.com
 

By object constructor:

Syntax:

var objectName=new Object();

Example:

<html>
<body>
<script>  
var student=new Object();  
student.rollNo = "MCA/07/06",  
student.name= "Jai"
document.write("Name: " +student.name + "</br>");  
document.write("RollNo: " + student.rollNo);  
</script> 
</body>
</html>

Try it:

JS Bin on jsbin.com
 

By User-Defined Function:

We have to use this keyword to refer the object that has been passed to a function.

Example:

<html>
<body>
<script>  
function Student(name,rollNo){  
this.name=name;  
this.rollNo=rollNo;   
}  
var student=new Student("Jai", "MCA/07/06");    
document.write("Name: " +student.name + "</br>");  
document.write("RollNo: " + student.rollNo);    
</script>  
</body>
</html>

Try it:

JS Bin on jsbin.com
 

How to add method to javascript object:

We can add a method to JavaScript object. First define a method and then assign that method as a property to object.

Example:

<html>
<body>
<script> 
function stuClassName(className){  
this.className=className;     
}  
function Student(name,rollNo){  
this.name=name;  
this.rollNo=rollNo; 
this.stuClassName= stuClassName;  
}  
var student=new Student("Jai", "MCA/07/06"); 
student.stuClassName("MCA Final");
document.write("Name: " +student.name + "</br>");  
document.write("RollNo: " + student.rollNo + "</br>");  
document.write("Class: " + student.className);      
</script>  
</body>
</html>

Try it:

JS Bin on jsbin.com