DEV Community

Randy Rivera
Randy Rivera

Posted on

Understanding the Constructor Property

  • There is a special constructor property located on the object instance beagle that was created in the previous posts:
let beagle = new Dog();

console.log(beagle.constructor === Dog);
Enter fullscreen mode Exit fullscreen mode
  • This console.log calls would display true in the console.

  • Note that the constructor property is a reference to the constructor function that created the instance. The advantage of the constructor property is that it's possible to check for this property to find out what kind of object it is.

  • Here's an example of how this could be used:

function joinDogFraternity(candidate) {
   if (candidate.constructor === Dog) {
     return true;
   } else {
     return false;
   }
}
Enter fullscreen mode Exit fullscreen mode
  • Here I just wrote a joinDogFraternity function that takes a candidate parameter and, using the constructor property, return true if the candidate is a Dog, otherwise return false.
  • Note: Since the constructor property can be overwritten (which will be covered in the next two posts) it’s generally better to use the instanceof method to check the type of an object.

Top comments (0)