JavaScript User Defined Object
There are 3 ways to create objects:
- Create using object literal
- Create an instance of the Object directly (with 'new' keyword)
- Using an object constructor (with 'new' keyword)
Creating object using object literal
Syntax:
object_name = {property1:value1,property2:value2,...,property'n':value'n'};
Values from the object are accessed using '.'(dot).
Eg:
<script>
var student_data = {Student_ID:"1234",Course:"BCA", Year:"2021", Merit:"yes"};
alert(student_data.Year); // alerts 2021
</script>
Creating instance of an object directly
We create an object using the 'new' keyword.
<script>
var student_data = new Object();
student_data.Student_ID=1234;
student_data.Course = "BCA";
student_data.Year = 2021;
student_data.Merit = "yes";
alert(student_data.Student_ID);// alerts 1234
</script>
Creating an object using constructor
We create a constructor function with arguments. Each argument is assigned with values using 'this'. We can create multiple objects with the constructor function.
<script>
function Student_data(Student_ID,Course,Year,Merit)
{
this.Student_ID = Student_ID;
this.Course = Course;
this.Year = Year;
this.Merit = Merit;
}
var obj = new Student_data(1234,"BCA",2021,"yes");
alert(obj.Merit); // alerts yes
</script>
We create object types by calling the constructor function with the 'new' keyword.