DEV Community

Kabir Nazir
Kabir Nazir

Posted on • Edited on

Prototype in Javascript - 03 - The new keyword

In the previous article, we saw how to create objects and set their prototypes using the internal __proto__ property. Let us now look at another way of creating objects and how we assign prototypes to it.

The new keyword

    function createUser(name, score) {
      let user = {};
      user.name = name;
      user.score = score;
      return user;
    }

    let user = createUser('Kabir', 5);
Enter fullscreen mode Exit fullscreen mode

If you look at the code of the createUser function, you could argue that it's a bit verbose. There are two lines of code, particularly that can be considered as boilerplate when writing functions to create objects. They are the first and last line in the function, namely

  1. let user = {};
  2. return user;

Javascript provides us a way to get rid of these lines of boilerplate code with the introduction of the new keyword. Let us see with an example.

    function User(name, score) {
      this.name = name;
      this.score = score;
    } 

    let user = new User('Kabir', 5);
Enter fullscreen mode Exit fullscreen mode

As you can see, the amount of code needed to create an object is made much simpler by using the new keyword. How does it do that? Basically, when you use 'new' before a function call, it tells Javascript to do a few things inside the function body.

  1. Create an empty object.
  2. Set the this inside the function to point to that object.
  3. Return that object at the end of the function.

In other words, you could say that new is a kind of syntactic sugar in Javascript when it comes to object creation. The two ways of creating a user object mentioned above work in exactly the same way under the hood in Javascript to create the object. There are however some minor differences when we use new (for example, the function name is capitalized to 'User'. Although this isn't compulsory, it is practiced by developers as a convention to let other people know that this function is meant to be used with the new keyword) but they aren't relevant to our topic at hand.

Now, you might be wondering, how does one set the __proto__ object when creating an object using the new keyword? The answer to that lies in a default property available in a Javascript function called prototype.

Function.prototype

All constructor functions in Javascript have a property called prototype. Please note that this is slightly different from the __proto__ or [[Prototype]] property of objects in a few ways (You can read more about that here). The prototype property of a function is used to assign the [[Prototype]] to the object that would be created when the new keyword is used with that function. Let us look at an example.

    function User(name, score) {
      this.name = name;
      this.score = score;
    } 

    let userFunctions = {
      incrementScore: function() {
        this.score++;
      }
    }

    User.prototype = userFunctions;

    let user = new User('Kabir', 5);
    user.incrementScore();
    console.log(user.score); // Outputs 6
Enter fullscreen mode Exit fullscreen mode

In the above code, we assign a custom object called userFunctions to User.prototype. By doing so, we are telling Javascript that whenever an object is created using new User(), then set the __proto__ of that object to userFunctions. In this way, we are able to set the prototypes for objects created through functions as well.

An important point to note is that it isn't wise to directly assign an object to the function prototype as this leads to the function's constructor value being overridden as well. This is because every function in Javascript has a default object for its prototype. This object holds the reference to a constructor, whose value you normally wouldn't want to be overwritten. Hence, a better way would be to set properties to the prototype as shown below.

    User.prototype.incrementScore = function() {
      this.score++;
    };
Enter fullscreen mode Exit fullscreen mode

In using the new keyword, we have seen that we write the code for the constructor function in one block and assign properties to its prototype in another block. There's a cleaner way to do both of these in Javascript in the same block of code, using classes. We shall see more about it in the next article of this series.

Top comments (0)