Object literals vs constructors in JavaScript



Object literals and constructors both are used to create an Object in JavaScript. An object created by the object literals is a singleton. This means when a change is made to the object, it affects that object across the entire script.

If an object created by a function constructor has multiple instances of the object. This means the changes made to one instance, will not affect other instances.

Object Literal Notation − Let’s create user details where we have the key, name, age, and name of the company. So we are creating an object named userDetails.

const userDetails = {name: "Aman", age: "22", Company: "tutorialspoint"};

Object Constructor Notation − In constructor Notation, we are creating the same object but in a different way. By calling the constructor function with the "new" keyword.

const userDetails = new User("Aman", 22, "tutorialspoint");

Methods and Properties

Objects in JavaScript have methods and properties, whether they are built with a constructor function or with literal notation. In JavaScript, the keyword called 'this' is the object that "possesses" the code. The value of this, when used in an object, is the object itself.

Let’s demonstrate how to define them.

Object Literal Notation −

const Tutorialspoint = {
   'url': " https://www.tutorialspoint.com/index.htm",
   'printUrl': function(){ 
      console.log(this.url);
   }
};

Object constructor Notation −

function Tutorialspoint(){
   this.url = " https://www.tutorialspoint.com/index.htm";
   this.printUrl = function(){
      console.log(this.url);
   }
}

Example 1

In the following example, we are creating an object and printing its value using literal notation.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Literal Notation</title>
</head>
<body>
   <script>
      const Tutorialspoint = {
         url: " https://www.tutorialspoint.com/index.htm",
         printUrl: function () {
            document.write(this.url);
         },
      };
      Tutorialspoint.printUrl(); //Literal Notation
   </script>
</body>
</html>

Example 2

In the following example, we are creating an object and printing its value using constructor notation.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Literal Notation</title>
</head>
<body>
   <script>
      function Tutorialspoint() {
         this.url = " https://www.tutorialspoint.com/index.htm";
         this.printUrl = function () {
            document.write(this.url);
         };
      }
      var link = new Tutorialspoint();
      link.printUrl(); //Literal Notation
   </script>
</body>
</html>

Advertisements