JavaScript Object
JavaScript is an object-based(object-oriented) programming language. JavaScript object is an entity that has different properties. For instance, a student is an object the has object properties ( Name, Sex, Age, Department, ID, etc. are properties of object student).
Creating an object by object literal
We can create a JavaScript object by separating Object property and values by a colon(:).
Syntax
{codeBox}objectname={property1:value1,property2:value2};
{codeBox}Example 1: Creating an object by using the above syntax.<script> student={name:"Abebe",sex:"Male",age:26,dep:"IT",ID:"IT235/10"}; document.write(student.ID+" "+student.name+" "+student.sex+" "+student.age+" "+student.dep); </script>
{codeBox}OutputCreating an object by creating an instance of an object
To create a JavaScript object by creating an instance of an object we use the new keyword.
Syntax
{codeBox}let objectname= new object();
{codeBox}Example 2: Creating the JavaScript object by using the constructor.<html> <body> <script> function student(id,name,sex,dep){ this.id=id; this.name=name; this.sex=sex; this.dep=dep; } s=new student(235,"Abebe","Male","IT"); document.write(s.id+" "+s.name+" "+s.sex+" "+s.dep); </script> </body> </html>
{codeBox}Output
0 Comments