- There is a special
constructorproperty located on the object instance beagle that was created in the previous posts:
let beagle = new Dog();
console.log(beagle.constructor === Dog);
This
console.logcalls would displaytruein the console.Note that the
constructorproperty is a reference to the constructor function that created the instance. The advantage of theconstructorproperty 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;
}
}
- Here I just wrote a
joinDogFraternityfunction that takes acandidateparameter and, using theconstructorproperty, returntrueif the candidate is aDog, otherwise returnfalse. - Note: Since the
constructorproperty can be overwritten (which will be covered in the next two posts) it’s generally better to use theinstanceofmethod to check the type of an object.
Top comments (0)