What is the main difference between objects created using object literal and constructor function?


Objects created using object literal are singletons, this means when a change is made to the object, it affects the object entire the script. Whereas if an object is created using constructor function and a change is made to it, that change won't affect the object throughout the script.

 Let's discuss them individually.

1) Objects created using object literal

Since these are singletons, a change to an object persists throughout the script. A change in one instance will affect all the instances of the object. 

In the following example if we observe, both the objects "student" and "newStudent" display the same name(Ravi) initially. But once the name of object "newstudent" is changed(keeping the other object name constant), both the objects have displayed the changed name (kumar)

Example

Live Demo

<html>
<body>
<script>
   var student = {
      name: "Ravi"
   }
   var newStudent = student;
   document.write("Before change");
   document.write("</br>");
   document.write("student name = " + student.name);
   document.write("</br>");
   document.write("new student name = " + newStudent.name);
   document.write("</br>");
   newStudent.name = "kumar";
   document.write("After change");
   document.write("</br>");
   document.write("student name = " + student.name);
   document.write("</br>");
   document.write("new student name = " + newStudent.name);
</script>
</body>
</html>

Output

Before change
student name = Ravi
new student name = Ravi
After change
student name = kumar
new student name = kumar


2) Objects created using constructor function.

Object defined with a function constructor lets you have multiple instances of that object. This means change made to one instance, will not affect other instances.

In the following example even though the name of object "newStudent" has changed, the name of other object "student" remained the same. Both the objects displayed different names as shown in the output.

Example

Live Demo

<html>
<body>
<script>
   var stu = function() {
      this.name= "Ravi"
   }
   var newStudent = new stu();
   var student = new stu();
   document.write("Before change");
   document.write("<br>");
   document.write("student name = " + student.name);
   document.write("<br>");
   document.write("new student name = " + newStudent.name);
   document.write("<br>");
   newStudent.name = "kumar";
   document.write("After change");
   document.write("<br>");
   document.write("student name = " + student.name);
   document.write("<br>");
   document.write("new student name = " + newStudent.name);
</script>
</body>
</html>

Output

Before change
student name = Ravi
new student name = Ravi
After change
student name = Ravi
new student name = kumar
raja
Published on 19-Jun-2019 14:02:55
Advertisements