DEV Community

Randy Rivera
Randy Rivera

Posted on • Updated on

Extend Constructors to Receive Arguments

  • Continued
  • The Dog constructor from the last post worked well. However, notice that all Dogs that are created with the Dog constructor are automatically named Anakin, are brown in color, and have four legs. What if you want dogs with different values for name and color? It's possible to change the properties of each dog manually but that would be a lot of work:
let husky = new Dog();
husky.name = "Rex";
husky.color = "blue";
Enter fullscreen mode Exit fullscreen mode
  • Suppose you were writing a program to keep track of hundreds or even thousands of different dogs in an aviary. It would take a lot of time to create all the dogs, then change the properties to different values for every one. To more easily create different Dog objects, you can design your Dog constructor to accept parameters:
function Dog(name, color) {
  this.name = name;
  this.color = color;
  this.numLegs = 4;
}

let terrier = new Dog("Ewok", "tan");
Enter fullscreen mode Exit fullscreen mode
  • Then pass in the values as arguments to define each unique dog into the Dog constructor: let terrier = new Dog("Ewok", "tan"); This gives a new instance of Dog with name and color properties set to Ewok and tan, respectively. The numLegs property is still set to 4. The terrier has these properties:
console.log(terrier.name); // will print out Ewok
console.log(terrier.color); // will print out tan
console.log(terrier.numLegs); // will print out 4
Enter fullscreen mode Exit fullscreen mode
  • The constructor is more flexible. It's now possible to define the properties for each Dog at the time it is created, which is one way that JavaScript constructors are so useful. They group objects together based on shared characteristics and behavior and define a blueprint that automates their creation.

Top comments (0)

Some comments have been hidden by the post's author - find out more