Using a Constructor to Create Objects

rthefounding

Randy Rivera

Posted on June 8, 2021

Using a Constructor to Create Objects
  • Continued.
  • Here's the Dog constructor from the previous post:
function Dog() {
  this.name = "Anakin";
  this.color = "brown";
  this.numLegs = 4;
}

let hound = new Dog();
Enter fullscreen mode Exit fullscreen mode

NOTE: this inside the constructor always refers to the object being created.

  • Notice that the new operator is used when calling a constructor. This tells JavaScript to create a new instance of Dog called hound. Without the new operator, this inside the constructor would not point to the newly created object, giving unexpected results. Now hound has all the properties defined inside the Dog constructor:
hound.name; // when console.log it will print out Anakin
hound.color; // when console.log it will print out brown
hound.numLegs; // whem console.log it will print out 4
Enter fullscreen mode Exit fullscreen mode
  • Just like any other object, its properties can be accessed and modified:
hound.name = 'Obi-Wan Kenobi';
console.log(hound.name); // will print out Obi-Wan Kenobi
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
rthefounding
Randy Rivera

Posted on June 8, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related