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:

Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki