A constructor is just a function that can be used to create any number of objects with the same properties. Constructor names usually are expected to begin with a capital letter.

↓ Example ↓
// create the constructor
function Flight(airlines, flightNumber) {
    this.airlines = airlines;
    this.flightNumber = flightNumber;

    this.display = function() {

let flight1 = new Flight("American Airlines", "AA123");
let flight2 = new Flight("Southwest", "SW497");

flight1.display(); //    RESULT: "American Airlines" "AA123"        
flight2.display(); //    RESULT: "Southwest" "SW497"

Use instanceof to check if an Object is an instance of a constructor.

console.log(flight1 instanceof Flight)
//    RESULT: returns true

console.log(flight2 instanceof Flight)
//    RESULT: returns true

NOTE: While instanceof is generally the preferred method, it is possible to instead use .constructor === TypeName instead.

console.log(flight1.constructor === Flight)        
// RESULT: returns true

NOTE: You can return an object from a constructor if you want, but if you try to return a primative type, like a number or string, the JavaScript engine will ignore it.

NOTE: You can use accessor types inside of the constructor and each new object the constructor creates will carry these settings.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

↑ Back to Top