CodesJava

Easy learning with example program codes

How to create javascript 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
 

Related topics:



Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap